} else { startIndex = sourceHeader ? 1 : 0; } if (!dimensionsDefine && startIndex === 1) { dimensionsDefine = []; arrayRowsTravelFirst(function (val, index) { dimensionsDefine[index] = val != null ? val : ''; }, seriesLayoutBy, data); } dimensionsDetectCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? data.length : data[0] ? data[0].length : null; } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { if (!dimensionsDefine) { dimensionsDefine = objectRowsCollectDimensions(data); findPotentialName = true; } } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) { if (!dimensionsDefine) { dimensionsDefine = []; findPotentialName = true; each$1(data, function (colArr, key) { dimensionsDefine.push(key); }); } } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) { var value0 = getDataItemValue(data[0]); dimensionsDetectCount = isArray(value0) && value0.length || 1; } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) { if (__DEV__) { assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.'); } } var potentialNameDimIndex; if (findPotentialName) { each$1(dimensionsDefine, function (dim, idx) { if ((isObject$1(dim) ? dim.name : dim) === 'name') { potentialNameDimIndex = idx; } }); } return { startIndex: startIndex, dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine), dimensionsDetectCount: dimensionsDetectCount, potentialNameDimIndex: potentialNameDimIndex // TODO: potentialIdDimIdx }; } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'], // which is reasonable. But dimension name is duplicated. // Returns undefined or an array contains only object without null/undefiend or string. function normalizeDimensionsDefine(dimensionsDefine) { if (!dimensionsDefine) { // The meaning of null/undefined is different from empty array. return; } var nameMap = createHashMap(); return map(dimensionsDefine, function (item, index) { item = extend({}, isObject$1(item) ? item : {name: item}); // User can set null in dimensions. // We dont auto specify name, othewise a given name may // cause it be refered unexpectedly. if (item.name == null) { return item; } // Also consider number form like 2012. item.name += ''; // User may also specify displayName. // displayName will always exists except user not // specified or dim name is not specified or detected. // (A auto generated dim name will not be used as // displayName). if (item.displayName == null) { item.displayName = item.name; } var exist = nameMap.get(item.name); if (!exist) { nameMap.set(item.name, {count: 1}); } else { item.name += '-' + exist.count++; } return item; }); } function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) { maxLoop == null && (maxLoop = Infinity); if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) { for (var i = 0; i < data.length && i < maxLoop; i++) { cb(data[i] ? data[i][0] : null, i); } } else { var value0 = data[0] || []; for (var i = 0; i < value0.length && i < maxLoop; i++) { cb(value0[i], i); } } } function objectRowsCollectDimensions(data) { var firstIndex = 0; var obj; while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line if (obj) { var dimensions = []; each$1(obj, function (value, key) { dimensions.push(key); }); return dimensions; } } // ??? TODO merge to completedimensions, where also has // default encode making logic. And the default rule // should depends on series? consider 'map'. function makeDefaultEncode( seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult ) { var coordSysDefine = getCoordSysDefineBySeries(seriesModel); var encode = {}; // var encodeTooltip = []; // var encodeLabel = []; var encodeItemName = []; var encodeSeriesName = []; var seriesType = seriesModel.subType; // ??? TODO refactor: provide by series itself. // Consider the case: 'map' series is based on geo coordSys, // 'graph', 'heatmap' can be based on cartesian. But can not // give default rule simply here. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']); var cSeriesMap = createHashMap([ 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot' ]); // Usually in this case series will use the first data // dimension as the "value" dimension, or other default // processes respectively. if (coordSysDefine && cSeriesMap.get(seriesType) != null) { var ecModel = seriesModel.ecModel; var datasetMap = inner$3(ecModel).datasetMap; var key = datasetModel.uid + '_' + seriesLayoutBy; var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0}); // TODO // Auto detect first time axis and do arrangement. each$1(coordSysDefine.coordSysDims, function (coordDim) { // In value way. if (coordSysDefine.firstCategoryDimIndex == null) { var dataDim = datasetRecord.valueWayDim++; encode[coordDim] = dataDim; // ??? TODO give a better default series name rule? // especially when encode x y specified. // consider: when mutiple series share one dimension // category axis, series name should better use // the other dimsion name. On the other hand, use // both dimensions name. encodeSeriesName.push(dataDim); // encodeTooltip.push(dataDim); // encodeLabel.push(dataDim); } // In category way, category axis. else if (coordSysDefine.categoryAxisMap.get(coordDim)) { encode[coordDim] = 0; encodeItemName.push(0); } // In category way, non-category axis. else { var dataDim = datasetRecord.categoryWayDim++; encode[coordDim] = dataDim; // encodeTooltip.push(dataDim); // encodeLabel.push(dataDim); encodeSeriesName.push(dataDim); } }); } // Do not make a complex rule! Hard to code maintain and not necessary. // ??? TODO refactor: provide by series itself. // [{name: ..., value: ...}, ...] like: else if (nSeriesMap.get(seriesType) != null) { // Find the first not ordinal. (5 is an experience value) var firstNotOrdinal; for (var i = 0; i < 5 && firstNotOrdinal == null; i++) { if (!doGuessOrdinal( data, sourceFormat, seriesLayoutBy, completeResult.dimensionsDefine, completeResult.startIndex, i )) { firstNotOrdinal = i; } } if (firstNotOrdinal != null) { encode.value = firstNotOrdinal; var nameDimIndex = completeResult.potentialNameDimIndex || Math.max(firstNotOrdinal - 1, 0); // By default, label use itemName in charts. // So we dont set encodeLabel here. encodeSeriesName.push(nameDimIndex); encodeItemName.push(nameDimIndex); // encodeTooltip.push(firstNotOrdinal); } } // encodeTooltip.length && (encode.tooltip = encodeTooltip); // encodeLabel.length && (encode.label = encodeLabel); encodeItemName.length && (encode.itemName = encodeItemName); encodeSeriesName.length && (encode.seriesName = encodeSeriesName); return encode; } /** * If return null/undefined, indicate that should not use datasetModel. */ function getDatasetModel(seriesModel) { var option = seriesModel.option; // Caution: consider the scenario: // A dataset is declared and a series is not expected to use the dataset, // and at the beginning `setOption({series: { noData })` (just prepare other // option but no data), then `setOption({series: {data: [...]}); In this case, // the user should set an empty array to avoid that dataset is used by default. var thisData = option.data; if (!thisData) { return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0); } } /** * The rule should not be complex, otherwise user might not * be able to known where the data is wrong. * The code is ugly, but how to make it neat? * * @param {module:echars/data/Source} source * @param {number} dimIndex * @return {boolean} Whether ordinal. */ function guessOrdinal(source, dimIndex) { return doGuessOrdinal( source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex ); } // dimIndex may be overflow source data. function doGuessOrdinal( data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex ) { var result; // Experience value. var maxLoop = 5; if (isTypedArray(data)) { return false; } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine // always exists in source. var dimName; if (dimensionsDefine) { dimName = dimensionsDefine[dimIndex]; dimName = isObject$1(dimName) ? dimName.name : dimName; } if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) { if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) { var sample = data[dimIndex]; for (var i = 0; i < (sample || []).length && i < maxLoop; i++) { if ((result = detectValue(sample[startIndex + i])) != null) { return result; } } } else { for (var i = 0; i < data.length && i < maxLoop; i++) { var row = data[startIndex + i]; if (row && (result = detectValue(row[dimIndex])) != null) { return result; } } } } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) { if (!dimName) { return; } for (var i = 0; i < data.length && i < maxLoop; i++) { var item = data[i]; if (item && (result = detectValue(item[dimName])) != null) { return result; } } } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) { if (!dimName) { return; } var sample = data[dimName]; if (!sample || isTypedArray(sample)) { return false; } for (var i = 0; i < sample.length && i < maxLoop; i++) { if ((result = detectValue(sample[i])) != null) { return result; } } } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) { for (var i = 0; i < data.length && i < maxLoop; i++) { var item = data[i]; var val = getDataItemValue(item); if (!isArray(val)) { return false; } if ((result = detectValue(val[dimIndex])) != null) { return result; } } } function detectValue(val) { // Consider usage convenience, '1', '2' will be treated as "number". // `isFinit('')` get `true`. if (val != null && isFinite(val) && val !== '') { return false; } else if (isString(val) && val !== '-') { return true; } } return false; } /** * ECharts global model * * @module {echarts/model/Global} */ /** * Caution: If the mechanism should be changed some day, these cases * should be considered: * * (1) In `merge option` mode, if using the same option to call `setOption` * many times, the result should be the same (try our best to ensure that). * (2) In `merge option` mode, if a component has no id/name specified, it * will be merged by index, and the result sequence of the components is * consistent to the original sequence. * (3) `reset` feature (in toolbox). Find detailed info in comments about * `mergeOption` in module:echarts/model/OptionManager. */ var OPTION_INNER_KEY = '\0_ec_inner'; /** * @alias module:echarts/model/Global * * @param {Object} option * @param {module:echarts/model/Model} parentModel * @param {Object} theme */ var GlobalModel = Model.extend({ constructor: GlobalModel, init: function (option, parentModel, theme, optionManager) { theme = theme || {}; this.option = null; // Mark as not initialized. /** * @type {module:echarts/model/Model} * @private */ this._theme = new Model(theme); /** * @type {module:echarts/model/OptionManager} */ this._optionManager = optionManager; }, setOption: function (option, optionPreprocessorFuncs) { assert$1( !(OPTION_INNER_KEY in option), 'please use chart.getOption()' ); this._optionManager.setOption(option, optionPreprocessorFuncs); this.resetOption(null); }, /** * @param {string} type null/undefined: reset all. * 'recreate': force recreate all. * 'timeline': only reset timeline option * 'media': only reset media query option * @return {boolean} Whether option changed. */ resetOption: function (type) { var optionChanged = false; var optionManager = this._optionManager; if (!type || type === 'recreate') { var baseOption = optionManager.mountOption(type === 'recreate'); if (!this.option || type === 'recreate') { initBase.call(this, baseOption); } else { this.restoreData(); this.mergeOption(baseOption); } optionChanged = true; } if (type === 'timeline' || type === 'media') { this.restoreData(); } if (!type || type === 'recreate' || type === 'timeline') { var timelineOption = optionManager.getTimelineOption(this); timelineOption && (this.mergeOption(timelineOption), optionChanged = true); } if (!type || type === 'recreate' || type === 'media') { var mediaOptions = optionManager.getMediaOption(this, this._api); if (mediaOptions.length) { each$1(mediaOptions, function (mediaOption) { this.mergeOption(mediaOption, optionChanged = true); }, this); } } return optionChanged; }, /** * @protected */ mergeOption: function (newOption) { var option = this.option; var componentsMap = this._componentsMap; var newCptTypes = []; resetSourceDefaulter(this); // If no component class, merge directly. // For example: color, animaiton options, etc. each$1(newOption, function (componentOption, mainType) { if (componentOption == null) { return; } if (!ComponentModel.hasClass(mainType)) { // globalSettingTask.dirty(); option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true); } else if (mainType) { newCptTypes.push(mainType); } }); ComponentModel.topologicalTravel( newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this ); function visitComponent(mainType, dependencies) { var newCptOptionList = normalizeToArray(newOption[mainType]); var mapResult = mappingToExists( componentsMap.get(mainType), newCptOptionList ); makeIdAndName(mapResult); // Set mainType and complete subType. each$1(mapResult, function (item, index) { var opt = item.option; if (isObject$1(opt)) { item.keyInfo.mainType = mainType; item.keyInfo.subType = determineSubType(mainType, opt, item.exist); } }); var dependentModels = getComponentsByTypes( componentsMap, dependencies ); option[mainType] = []; componentsMap.set(mainType, []); each$1(mapResult, function (resultItem, index) { var componentModel = resultItem.exist; var newCptOption = resultItem.option; assert$1( isObject$1(newCptOption) || componentModel, 'Empty component definition' ); // Consider where is no new option and should be merged using {}, // see removeEdgeAndAdd in topologicalTravel and // ComponentModel.getAllClassMainTypes. if (!newCptOption) { componentModel.mergeOption({}, this); componentModel.optionUpdated({}, false); } else { var ComponentModelClass = ComponentModel.getClass( mainType, resultItem.keyInfo.subType, true ); if (componentModel && componentModel instanceof ComponentModelClass) { componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty(); componentModel.mergeOption(newCptOption, this); componentModel.optionUpdated(newCptOption, false); } else { // PENDING Global as parent ? var extraOpt = extend( { dependentModels: dependentModels, componentIndex: index }, resultItem.keyInfo ); componentModel = new ComponentModelClass( newCptOption, this, this, extraOpt ); extend(componentModel, extraOpt); componentModel.init(newCptOption, this, this, extraOpt); // Call optionUpdated after init. // newCptOption has been used as componentModel.option // and may be merged with theme and default, so pass null // to avoid confusion. componentModel.optionUpdated(null, true); } } componentsMap.get(mainType)[index] = componentModel; option[mainType][index] = componentModel.option; }, this); // Backup series for filtering. if (mainType === 'series') { createSeriesIndices(this, componentsMap.get('series')); } } this._seriesIndicesMap = createHashMap( this._seriesIndices = this._seriesIndices || [] ); }, /** * Get option for output (cloned option and inner info removed) * @public * @return {Object} */ getOption: function () { var option = clone(this.option); each$1(option, function (opts, mainType) { if (ComponentModel.hasClass(mainType)) { var opts = normalizeToArray(opts); for (var i = opts.length - 1; i >= 0; i--) { // Remove options with inner id. if (isIdInner(opts[i])) { opts.splice(i, 1); } } option[mainType] = opts; } }); delete option[OPTION_INNER_KEY]; return option; }, /** * @return {module:echarts/model/Model} */ getTheme: function () { return this._theme; }, /** * @param {string} mainType * @param {number} [idx=0] * @return {module:echarts/model/Component} */ getComponent: function (mainType, idx) { var list = this._componentsMap.get(mainType); if (list) { return list[idx || 0]; } }, /** * If none of index and id and name used, return all components with mainType. * @param {Object} condition * @param {string} condition.mainType * @param {string} [condition.subType] If ignore, only query by mainType * @param {number|Array.<number>} [condition.index] Either input index or id or name. * @param {string|Array.<string>} [condition.id] Either input index or id or name. * @param {string|Array.<string>} [condition.name] Either input index or id or name. * @return {Array.<module:echarts/model/Component>} */ queryComponents: function (condition) { var mainType = condition.mainType; if (!mainType) { return []; } var index = condition.index; var id = condition.id; var name = condition.name; var cpts = this._componentsMap.get(mainType); if (!cpts || !cpts.length) { return []; } var result; if (index != null) { if (!isArray(index)) { index = [index]; } result = filter(map(index, function (idx) { return cpts[idx]; }), function (val) { return !!val; }); } else if (id != null) { var isIdArray = isArray(id); result = filter(cpts, function (cpt) { return (isIdArray && indexOf(id, cpt.id) >= 0) || (!isIdArray && cpt.id === id); }); } else if (name != null) { var isNameArray = isArray(name); result = filter(cpts, function (cpt) { return (isNameArray && indexOf(name, cpt.name) >= 0) || (!isNameArray && cpt.name === name); }); } else { // Return all components with mainType result = cpts.slice(); } return filterBySubType(result, condition); }, /** * The interface is different from queryComponents, * which is convenient for inner usage. * * @usage * var result = findComponents( * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}} * ); * var result = findComponents( * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}} * ); * var result = findComponents( * {mainType: 'series'}, * function (model, index) {...} * ); * // result like [component0, componnet1, ...] * * @param {Object} condition * @param {string} condition.mainType Mandatory. * @param {string} [condition.subType] Optional. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName}, * where xxx is mainType. * If query attribute is null/undefined or has no index/id/name, * do not filtering by query conditions, which is convenient for * no-payload situations or when target of action is global. * @param {Function} [condition.filter] parameter: component, return boolean. * @return {Array.<module:echarts/model/Component>} */ findComponents: function (condition) { var query = condition.query; var mainType = condition.mainType; var queryCond = getQueryCond(query); var result = queryCond ? this.queryComponents(queryCond) : this._componentsMap.get(mainType); return doFilter(filterBySubType(result, condition)); function getQueryCond(q) { var indexAttr = mainType + 'Index'; var idAttr = mainType + 'Id'; var nameAttr = mainType + 'Name'; return q && ( q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null ) ? { mainType: mainType, // subType will be filtered finally. index: q[indexAttr], id: q[idAttr], name: q[nameAttr] } : null; } function doFilter(res) { return condition.filter ? filter(res, condition.filter) : res; } }, /** * @usage * eachComponent('legend', function (legendModel, index) { * ... * }); * eachComponent(function (componentType, model, index) { * // componentType does not include subType * // (componentType is 'xxx' but not 'xxx.aa') * }); * eachComponent( * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}, * function (model, index) {...} * ); * eachComponent( * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}, * function (model, index) {...} * ); * * @param {string|Object=} mainType When mainType is object, the definition * is the same as the method 'findComponents'. * @param {Function} cb * @param {*} context */ eachComponent: function (mainType, cb, context) { var componentsMap = this._componentsMap; if (typeof mainType === 'function') { context = cb; cb = mainType; componentsMap.each(function (components, componentType) { each$1(components, function (component, index) { cb.call(context, componentType, component, index); }); }); } else if (isString(mainType)) { each$1(componentsMap.get(mainType), cb, context); } else if (isObject$1(mainType)) { var queryResult = this.findComponents(mainType); each$1(queryResult, cb, context); } }, /** * @param {string} name * @return {Array.<module:echarts/model/Series>} */ getSeriesByName: function (name) { var series = this._componentsMap.get('series'); return filter(series, function (oneSeries) { return oneSeries.name === name; }); }, /** * @param {number} seriesIndex * @return {module:echarts/model/Series} */ getSeriesByIndex: function (seriesIndex) { return this._componentsMap.get('series')[seriesIndex]; }, /** * Get series list before filtered by type. * FIXME: rename to getRawSeriesByType? * * @param {string} subType * @return {Array.<module:echarts/model/Series>} */ getSeriesByType: function (subType) { var series = this._componentsMap.get('series'); return filter(series, function (oneSeries) { return oneSeries.subType === subType; }); }, /** * @return {Array.<module:echarts/model/Series>} */ getSeries: function () { return this._componentsMap.get('series').slice(); }, /** * @return {number} */ getSeriesCount: function () { return this._componentsMap.get('series').length; }, /** * After filtering, series may be different * frome raw series. * * @param {Function} cb * @param {*} context */ eachSeries: function (cb, context) { assertSeriesInitialized(this); each$1(this._seriesIndices, function (rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; cb.call(context, series, rawSeriesIndex); }, this); }, /** * Iterate raw series before filtered. * * @param {Function} cb * @param {*} context */ eachRawSeries: function (cb, context) { each$1(this._componentsMap.get('series'), cb, context); }, /** * After filtering, series may be different. * frome raw series. * * @parma {string} subType * @param {Function} cb * @param {*} context */ eachSeriesByType: function (subType, cb, context) { assertSeriesInitialized(this); each$1(this._seriesIndices, function (rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; if (series.subType === subType) { cb.call(context, series, rawSeriesIndex); } }, this); }, /** * Iterate raw series before filtered of given type. * * @parma {string} subType * @param {Function} cb * @param {*} context */ eachRawSeriesByType: function (subType, cb, context) { return each$1(this.getSeriesByType(subType), cb, context); }, /** * @param {module:echarts/model/Series} seriesModel */ isSeriesFiltered: function (seriesModel) { assertSeriesInitialized(this); return this._seriesIndicesMap.get(seriesModel.componentIndex) == null; }, /** * @return {Array.<number>} */ getCurrentSeriesIndices: function () { return (this._seriesIndices || []).slice(); }, /** * @param {Function} cb * @param {*} context */ filterSeries: function (cb, context) { assertSeriesInitialized(this); var filteredSeries = filter( this._componentsMap.get('series'), cb, context ); createSeriesIndices(this, filteredSeries); }, restoreData: function (payload) { var componentsMap = this._componentsMap; createSeriesIndices(this, componentsMap.get('series')); var componentTypes = []; componentsMap.each(function (components, componentType) { componentTypes.push(componentType); }); ComponentModel.topologicalTravel( componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType, dependencies) { each$1(componentsMap.get(componentType), function (component) { (componentType !== 'series' || !isNotTargetSeries(component, payload)) && component.restoreData(); }); } ); } }); function isNotTargetSeries(seriesModel, payload) { if (payload) { var index = payload.seiresIndex; var id = payload.seriesId; var name = payload.seriesName; return (index != null && seriesModel.componentIndex !== index) || (id != null && seriesModel.id !== id) || (name != null && seriesModel.name !== name); } } /** * @inner */ function mergeTheme(option, theme) { // PENDING // NOT use `colorLayer` in theme if option has `color` var notMergeColorLayer = option.color && !option.colorLayer; each$1(theme, function (themeItem, name) { if (name === 'colorLayer' && notMergeColorLayer) { return; } // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理 if (!ComponentModel.hasClass(name)) { if (typeof themeItem === 'object') { option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false); } else { if (option[name] == null) { option[name] = themeItem; } } } }); } function initBase(baseOption) { baseOption = baseOption; // Using OPTION_INNER_KEY to mark that this option can not be used outside, // i.e. `chart.setOption(chart.getModel().option);` is forbiden. this.option = {}; this.option[OPTION_INNER_KEY] = 1; /** * Init with series: [], in case of calling findSeries method * before series initialized. * @type {Object.<string, Array.<module:echarts/model/Model>>} * @private */ this._componentsMap = createHashMap({series: []}); /** * Mapping between filtered series list and raw series list. * key: filtered series indices, value: raw series indices. * @type {Array.<nubmer>} * @private */ this._seriesIndices; this._seriesIndicesMap; mergeTheme(baseOption, this._theme.option); // TODO Needs clone when merging to the unexisted property merge(baseOption, globalDefault, false); this.mergeOption(baseOption); } /** * @inner * @param {Array.<string>|string} types model types * @return {Object} key: {string} type, value: {Array.<Object>} models */ function getComponentsByTypes(componentsMap, types) { if (!isArray(types)) { types = types ? [types] : []; } var ret = {}; each$1(types, function (type) { ret[type] = (componentsMap.get(type) || []).slice(); }); return ret; } /** * @inner */ function determineSubType(mainType, newCptOption, existComponent) { var subType = newCptOption.type ? newCptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent. : ComponentModel.determineSubType(mainType, newCptOption); // tooltip, markline, markpoint may always has no subType return subType; } /** * @inner */ function createSeriesIndices(ecModel, seriesModels) { ecModel._seriesIndicesMap = createHashMap( ecModel._seriesIndices = map(seriesModels, function (series) { return series.componentIndex; }) || [] ); } /** * @inner */ function filterBySubType(components, condition) { // Using hasOwnProperty for restrict. Consider // subType is undefined in user payload. return condition.hasOwnProperty('subType') ? filter(components, function (cpt) { return cpt.subType === condition.subType; }) : components; } /** * @inner */ function assertSeriesInitialized(ecModel) { // Components that use _seriesIndices should depends on series component, // which make sure that their initialization is after series. if (__DEV__) { if (!ecModel._seriesIndices) { throw new Error('Option should contains series.'); } } } mixin(GlobalModel, colorPaletteMixin); var echartsAPIList = [ 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption', 'getViewOfComponentModel', 'getViewOfSeriesModel' ]; // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js function ExtensionAPI(chartInstance) { each$1(echartsAPIList, function (name) { this[name] = bind(chartInstance[name], chartInstance); }, this); } var coordinateSystemCreators = {}; function CoordinateSystemManager() { this._coordinateSystems = []; } CoordinateSystemManager.prototype = { constructor: CoordinateSystemManager, create: function (ecModel, api) { var coordinateSystems = []; each$1(coordinateSystemCreators, function (creater, type) { var list = creater.create(ecModel, api); coordinateSystems = coordinateSystems.concat(list || []); }); this._coordinateSystems = coordinateSystems; }, update: function (ecModel, api) { each$1(this._coordinateSystems, function (coordSys) { coordSys.update && coordSys.update(ecModel, api); }); }, getCoordinateSystems: function () { return this._coordinateSystems.slice(); } }; CoordinateSystemManager.register = function (type, coordinateSystemCreator) { coordinateSystemCreators[type] = coordinateSystemCreator; }; CoordinateSystemManager.get = function (type) { return coordinateSystemCreators[type]; }; /** * ECharts option manager * * @module {echarts/model/OptionManager} */ var each$4 = each$1; var clone$3 = clone; var map$1 = map; var merge$1 = merge; var QUERY_REG = /^(min|max)?(.+)$/; /** * TERM EXPLANATIONS: * * [option]: * * An object that contains definitions of components. For example: * var option = { * title: {...}, * legend: {...}, * visualMap: {...}, * series: [ * {data: [...]}, * {data: [...]}, * ... * ] * }; * * [rawOption]: * * An object input to echarts.setOption. 'rawOption' may be an * 'option', or may be an object contains multi-options. For example: * var option = { * baseOption: { * title: {...}, * legend: {...}, * series: [ * {data: [...]}, * {data: [...]}, * ... * ] * }, * timeline: {...}, * options: [ * {title: {...}, series: {data: [...]}}, * {title: {...}, series: {data: [...]}}, * ... * ], * media: [ * { * query: {maxWidth: 320}, * option: {series: {x: 20}, visualMap: {show: false}} * }, * { * query: {minWidth: 320, maxWidth: 720}, * option: {series: {x: 500}, visualMap: {show: true}} * }, * { * option: {series: {x: 1200}, visualMap: {show: true}} * } * ] * }; * * @alias module:echarts/model/OptionManager * @param {module:echarts/ExtensionAPI} api */ function OptionManager(api) { /** * @private * @type {module:echarts/ExtensionAPI} */ this._api = api; /** * @private * @type {Array.<number>} */ this._timelineOptions = []; /** * @private * @type {Array.<Object>} */ this._mediaList = []; /** * @private * @type {Object} */ this._mediaDefault; /** * -1, means default. * empty means no media. * @private * @type {Array.<number>} */ this._currentMediaIndices = []; /** * @private * @type {Object} */ this._optionBackup; /** * @private * @type {Object} */ this._newBaseOption; } // timeline.notMerge is not supported in ec3. Firstly there is rearly // case that notMerge is needed. Secondly supporting 'notMerge' requires // rawOption cloned and backuped when timeline changed, which does no // good to performance. What's more, that both timeline and setOption // method supply 'notMerge' brings complex and some problems. // Consider this case: // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false); // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false); OptionManager.prototype = { constructor: OptionManager, /** * @public * @param {Object} rawOption Raw option. * @param {module:echarts/model/Global} ecModel * @param {Array.<Function>} optionPreprocessorFuncs * @return {Object} Init option */ setOption: function (rawOption, optionPreprocessorFuncs) { if (rawOption) { // That set dat primitive is dangerous if user reuse the data when setOption again. each$1(normalizeToArray(rawOption.series), function (series) { series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data); }); } // Caution: some series modify option data, if do not clone, // it should ensure that the repeat modify correctly // (create a new object when modify itself). rawOption = clone$3(rawOption, true); // FIXME // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。 var oldOptionBackup = this._optionBackup; var newParsedOption = parseRawOption.call( this, rawOption, optionPreprocessorFuncs, !oldOptionBackup ); this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode); if (oldOptionBackup) { // Only baseOption can be merged. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption); // For simplicity, timeline options and media options do not support merge, // that is, if you `setOption` twice and both has timeline options, the latter // timeline opitons will not be merged to the formers, but just substitude them. if (newParsedOption.timelineOptions.length) { oldOptionBackup.timelineOptions = newParsedOption.timelineOptions; } if (newParsedOption.mediaList.length) { oldOptionBackup.mediaList = newParsedOption.mediaList; } if (newParsedOption.mediaDefault) { oldOptionBackup.mediaDefault = newParsedOption.mediaDefault; } } else { this._optionBackup = newParsedOption; } }, /** * @param {boolean} isRecreate * @return {Object} */ mountOption: function (isRecreate) { var optionBackup = this._optionBackup; // TODO // 如果没有reset功能则不clone。 this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3); this._mediaList = map$1(optionBackup.mediaList, clone$3); this._mediaDefault = clone$3(optionBackup.mediaDefault); this._currentMediaIndices = []; return clone$3(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption` // called, and is merged into every new option by inner method `mergeOption` // each time `setOption` called, can be only used in `isRecreate`, because // its reliability is under suspicion. In other cases option merge is // performed by `model.mergeOption`. ? optionBackup.baseOption : this._newBaseOption ); }, /** * @param {module:echarts/model/Global} ecModel * @return {Object} */ getTimelineOption: function (ecModel) { var option; var timelineOptions = this._timelineOptions; if (timelineOptions.length) { // getTimelineOption can only be called after ecModel inited, // so we can get currentIndex from timelineModel. var timelineModel = ecModel.getComponent('timeline'); if (timelineModel) { option = clone$3( timelineOptions[timelineModel.getCurrentIndex()], true ); } } return option; }, /** * @param {module:echarts/model/Global} ecModel * @return {Array.<Object>} */ getMediaOption: function (ecModel) { var ecWidth = this._api.getWidth(); var ecHeight = this._api.getHeight(); var mediaList = this._mediaList; var mediaDefault = this._mediaDefault; var indices = []; var result = []; // No media defined. if (!mediaList.length && !mediaDefault) { return result; } // Multi media may be applied, the latter defined media has higher priority. for (var i = 0, len = mediaList.length; i < len; i++) { if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) { indices.push(i); } } // FIXME // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。 if (!indices.length && mediaDefault) { indices = [-1]; } if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) { result = map$1(indices, function (index) { return clone$3( index === -1 ? mediaDefault.option : mediaList[index].option ); }); } // Otherwise return nothing. this._currentMediaIndices = indices; return result; } }; function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) { var timelineOptions = []; var mediaList = []; var mediaDefault; var baseOption; // Compatible with ec2. var timelineOpt = rawOption.timeline; if (rawOption.baseOption) { baseOption = rawOption.baseOption; } // For timeline if (timelineOpt || rawOption.options) { baseOption = baseOption || {}; timelineOptions = (rawOption.options || []).slice(); } // For media query if (rawOption.media) { baseOption = baseOption || {}; var media = rawOption.media; each$4(media, function (singleMedia) { if (singleMedia && singleMedia.option) { if (singleMedia.query) { mediaList.push(singleMedia); } else if (!mediaDefault) { // Use the first media default. mediaDefault = singleMedia; } } }); } // For normal option if (!baseOption) { baseOption = rawOption; } // Set timelineOpt to baseOption in ec3, // which is convenient for merge option. if (!baseOption.timeline) { baseOption.timeline = timelineOpt; } // Preprocess. each$4([baseOption].concat(timelineOptions) .concat(map(mediaList, function (media) { return media.option; })), function (option) { each$4(optionPreprocessorFuncs, function (preProcess) { preProcess(option, isNew); }); } ); return { baseOption: baseOption, timelineOptions: timelineOptions, mediaDefault: mediaDefault, mediaList: mediaList }; } /** * @see <http://www.w3.org/TR/css3-mediaqueries/#media1> * Support: width, height, aspectRatio * Can use max or min as prefix. */ function applyMediaQuery(query, ecWidth, ecHeight) { var realMap = { width: ecWidth, height: ecHeight, aspectratio: ecWidth / ecHeight // lowser case for convenientce. }; var applicatable = true; each$1(query, function (value, attr) { var matched = attr.match(QUERY_REG); if (!matched || !matched[1] || !matched[2]) { return; } var operator = matched[1]; var realAttr = matched[2].toLowerCase(); if (!compare(realMap[realAttr], value, operator)) { applicatable = false; } }); return applicatable; } function compare(real, expect, operator) { if (operator === 'min') { return real >= expect; } else if (operator === 'max') { return real <= expect; } else { // Equals return real === expect; } } function indicesEquals(indices1, indices2) { // indices is always order by asc and has only finite number. return indices1.join(',') === indices2.join(','); } /** * Consider case: * `chart.setOption(opt1);` * Then user do some interaction like dataZoom, dataView changing. * `chart.setOption(opt2);` * Then user press 'reset button' in toolbox. * * After doing that all of the interaction effects should be reset, the * chart should be the same as the result of invoke * `chart.setOption(opt1); chart.setOption(opt2);`. * * Although it is not able ensure that * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to * `chart.setOption(merge(opt1, opt2));` exactly, * this might be the only simple way to implement that feature. * * MEMO: We've considered some other approaches: * 1. Each model handle its self restoration but not uniform treatment. * (Too complex in logic and error-prone) * 2. Use a shadow ecModel. (Performace expensive) */ function mergeOption(oldOption, newOption) { newOption = newOption || {}; each$4(newOption, function (newCptOpt, mainType) { if (newCptOpt == null) { return; } var oldCptOpt = oldOption[mainType]; if (!ComponentModel.hasClass(mainType)) { oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true); } else { newCptOpt = normalizeToArray(newCptOpt); oldCptOpt = normalizeToArray(oldCptOpt); var mapResult = mappingToExists(oldCptOpt, newCptOpt); oldOption[mainType] = map$1(mapResult, function (item) { return (item.option && item.exist) ? merge$1(item.exist, item.option, true) : (item.exist || item.option); }); } }); } var each$5 = each$1; var isObject$3 = isObject$1; var POSSIBLE_STYLES = [ 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine' ]; function compatEC2ItemStyle(opt) { var itemStyleOpt = opt && opt.itemStyle; if (!itemStyleOpt) { return; } for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) { var styleName = POSSIBLE_STYLES[i]; var normalItemStyleOpt = itemStyleOpt.normal; var emphasisItemStyleOpt = itemStyleOpt.emphasis; if (normalItemStyleOpt && normalItemStyleOpt[styleName]) { opt[styleName] = opt[styleName] || {}; if (!opt[styleName].normal) { opt[styleName].normal = normalItemStyleOpt[styleName]; } else { merge(opt[styleName].normal, normalItemStyleOpt[styleName]); } normalItemStyleOpt[styleName] = null; } if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) { opt[styleName] = opt[styleName] || {}; if (!opt[styleName].emphasis) { opt[styleName].emphasis = emphasisItemStyleOpt[styleName]; } else { merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]); } emphasisItemStyleOpt[styleName] = null; } } } function convertNormalEmphasis(opt, optType, useExtend) { if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) { var normalOpt = opt[optType].normal; var emphasisOpt = opt[optType].emphasis; if (normalOpt) { // Timeline controlStyle has other properties besides normal and emphasis if (useExtend) { opt[optType].normal = opt[optType].emphasis = null; defaults(opt[optType], normalOpt); } else { opt[optType] = normalOpt; } } if (emphasisOpt) { opt.emphasis = opt.emphasis || {}; opt.emphasis[optType] = emphasisOpt; } } } function removeEC3NormalStatus(opt) { convertNormalEmphasis(opt, 'itemStyle'); convertNormalEmphasis(opt, 'lineStyle'); convertNormalEmphasis(opt, 'areaStyle'); convertNormalEmphasis(opt, 'label'); convertNormalEmphasis(opt, 'labelLine'); // treemap convertNormalEmphasis(opt, 'upperLabel'); // graph convertNormalEmphasis(opt, 'edgeLabel'); } function compatTextStyle(opt, propName) { // Check whether is not object (string\null\undefined ...) var labelOptSingle = isObject$3(opt) && opt[propName]; var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle; if (textStyle) { for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) { var propName = TEXT_STYLE_OPTIONS[i]; if (textStyle.hasOwnProperty(propName)) { labelOptSingle[propName] = textStyle[propName]; } } } } function compatEC3CommonStyles(opt) { if (opt) { removeEC3NormalStatus(opt); compatTextStyle(opt, 'label'); opt.emphasis && compatTextStyle(opt.emphasis, 'label'); } } function processSeries(seriesOpt) { if (!isObject$3(seriesOpt)) { return; } compatEC2ItemStyle(seriesOpt); removeEC3NormalStatus(seriesOpt); compatTextStyle(seriesOpt, 'label'); // treemap compatTextStyle(seriesOpt, 'upperLabel'); // graph compatTextStyle(seriesOpt, 'edgeLabel'); if (seriesOpt.emphasis) { compatTextStyle(seriesOpt.emphasis, 'label'); // treemap compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph compatTextStyle(seriesOpt.emphasis, 'edgeLabel'); } var markPoint = seriesOpt.markPoint; if (markPoint) { compatEC2ItemStyle(markPoint); compatEC3CommonStyles(markPoint); } var markLine = seriesOpt.markLine; if (markLine) { compatEC2ItemStyle(markLine); compatEC3CommonStyles(markLine); } var markArea = seriesOpt.markArea; if (markArea) { compatEC3CommonStyles(markArea); } var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option, // then the backward compat based on option type will not be performed. if (seriesOpt.type === 'graph') { data = data || seriesOpt.nodes; var edgeData = seriesOpt.links || seriesOpt.edges; if (edgeData && !isTypedArray(edgeData)) { for (var i = 0; i < edgeData.length; i++) { compatEC3CommonStyles(edgeData[i]); } } each$1(seriesOpt.categories, function (opt) { removeEC3NormalStatus(opt); }); } if (data && !isTypedArray(data)) { for (var i = 0; i < data.length; i++) { compatEC3CommonStyles(data[i]); } } // mark point data var markPoint = seriesOpt.markPoint; if (markPoint && markPoint.data) { var mpData = markPoint.data; for (var i = 0; i < mpData.length; i++) { compatEC3CommonStyles(mpData[i]); } } // mark line data var markLine = seriesOpt.markLine; if (markLine && markLine.data) { var mlData = markLine.data; for (var i = 0; i < mlData.length; i++) { if (isArray(mlData[i])) { compatEC3CommonStyles(mlData[i][0]); compatEC3CommonStyles(mlData[i][1]); } else { compatEC3CommonStyles(mlData[i]); } } } // Series if (seriesOpt.type === 'gauge') { compatTextStyle(seriesOpt, 'axisLabel'); compatTextStyle(seriesOpt, 'title'); compatTextStyle(seriesOpt, 'detail'); } else if (seriesOpt.type === 'treemap') { convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle'); each$1(seriesOpt.levels, function (opt) { removeEC3NormalStatus(opt); }); } // sunburst starts from ec4, so it does not need to compat levels. } function toArr(o) { return isArray(o) ? o : o ? [o] : []; } function toObj(o) { return (isArray(o) ? o[0] : o) || {}; } var compatStyle = function (option, isTheme) { each$5(toArr(option.series), function (seriesOpt) { isObject$3(seriesOpt) && processSeries(seriesOpt); }); var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar']; isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis'); each$5( axes, function (axisName) { each$5(toArr(option[axisName]), function (axisOpt) { if (axisOpt) { compatTextStyle(axisOpt, 'axisLabel'); compatTextStyle(axisOpt.axisPointer, 'label'); } }); } ); each$5(toArr(option.parallel), function (parallelOpt) { var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault; compatTextStyle(parallelAxisDefault, 'axisLabel'); compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label'); }); each$5(toArr(option.calendar), function (calendarOpt) { convertNormalEmphasis(calendarOpt, 'itemStyle'); compatTextStyle(calendarOpt, 'dayLabel'); compatTextStyle(calendarOpt, 'monthLabel'); compatTextStyle(calendarOpt, 'yearLabel'); }); // radar.name.textStyle each$5(toArr(option.radar), function (radarOpt) { compatTextStyle(radarOpt, 'name'); }); each$5(toArr(option.geo), function (geoOpt) { if (isObject$3(geoOpt)) { compatEC3CommonStyles(geoOpt); each$5(toArr(geoOpt.regions), function (regionObj) { compatEC3CommonStyles(regionObj); }); } }); each$5(toArr(option.timeline), function (timelineOpt) { compatEC3CommonStyles(timelineOpt); convertNormalEmphasis(timelineOpt, 'label'); convertNormalEmphasis(timelineOpt, 'itemStyle'); convertNormalEmphasis(timelineOpt, 'controlStyle', true); var data = timelineOpt.data; isArray(data) && each$1(data, function (item) { if (isObject$1(item)) { convertNormalEmphasis(item, 'label'); convertNormalEmphasis(item, 'itemStyle'); } }); }); each$5(toArr(option.toolbox), function (toolboxOpt) { convertNormalEmphasis(toolboxOpt, 'iconStyle'); each$5(toolboxOpt.feature, function (featureOpt) { convertNormalEmphasis(featureOpt, 'iconStyle'); }); }); compatTextStyle(toObj(option.axisPointer), 'label'); compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); }; // Compatitable with 2.0 function get(opt, path) { path = path.split(','); var obj = opt; for (var i = 0; i < path.length; i++) { obj = obj && obj[path[i]]; if (obj == null) { break; } } return obj; } function set$1(opt, path, val, overwrite) { path = path.split(','); var obj = opt; var key; for (var i = 0; i < path.length - 1; i++) { key = path[i]; if (obj[key] == null) { obj[key] = {}; } obj = obj[key]; } if (overwrite || obj[path[i]] == null) { obj[path[i]] = val; } } function compatLayoutProperties(option) { each$1(LAYOUT_PROPERTIES, function (prop) { if (prop[0] in option && !(prop[1] in option)) { option[prop[1]] = option[prop[0]]; } }); } var LAYOUT_PROPERTIES = [ ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom'] ]; var COMPATITABLE_COMPONENTS = [ 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline' ]; var backwardCompat = function (option, isTheme) { compatStyle(option, isTheme); // Make sure series array for model initialization. option.series = normalizeToArray(option.series); each$1(option.series, function (seriesOpt) { if (!isObject$1(seriesOpt)) { return; } var seriesType = seriesOpt.type; if (seriesType === 'pie' || seriesType === 'gauge') { if (seriesOpt.clockWise != null) { seriesOpt.clockwise = seriesOpt.clockWise; } } if (seriesType === 'gauge') { var pointerColor = get(seriesOpt, 'pointer.color'); pointerColor != null && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor); } compatLayoutProperties(seriesOpt); }); // dataRange has changed to visualMap if (option.dataRange) { option.visualMap = option.dataRange; } each$1(COMPATITABLE_COMPONENTS, function (componentName) { var options = option[componentName]; if (options) { if (!isArray(options)) { options = [options]; } each$1(options, function (option) { compatLayoutProperties(option); }); } }); }; // (1) [Caution]: the logic is correct based on the premises: // data processing stage is blocked in stream. // See <module:echarts/stream/Scheduler#performDataProcessorTasks> // (2) Only register once when import repeatly. // Should be executed before after series filtered and before stack calculation. var dataStack = function (ecModel) { var stackInfoMap = createHashMap(); ecModel.eachSeries(function (seriesModel) { var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack. if (stack) { var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []); var data = seriesModel.getData(); var stackInfo = { // Used for calculate axis extent automatically. stackResultDimension: data.getCalculationInfo('stackResultDimension'), stackedOverDimension: data.getCalculationInfo('stackedOverDimension'), stackedDimension: data.getCalculationInfo('stackedDimension'), stackedByDimension: data.getCalculationInfo('stackedByDimension'), isStackedByIndex: data.getCalculationInfo('isStackedByIndex'), data: data, seriesModel: seriesModel }; // If stacked on axis that do not support data stack. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension) ) { return; } stackInfoList.length && data.setCalculationInfo( 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel ); stackInfoList.push(stackInfo); } }); stackInfoMap.each(calculateStack); }; function calculateStack(stackInfoList) { each$1(stackInfoList, function (targetStackInfo, idxInStack) { var resultVal = []; var resultNaN = [NaN, NaN]; var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension]; var targetData = targetStackInfo.data; var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes // depending on legend selection. var newData = targetData.map(dims, function (v0, v1, dataIndex) { var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver // should also be NaN, to draw a appropriate belt area. if (isNaN(sum)) { return resultNaN; } var byValue; var stackedDataRawIndex; if (isStackedByIndex) { stackedDataRawIndex = targetData.getRawIndex(dataIndex); } else { byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex); } // If stackOver is NaN, chart view will render point on value start. var stackedOver = NaN; for (var j = idxInStack - 1; j >= 0; j--) { var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`. if (!isStackedByIndex) { stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue); } if (stackedDataRawIndex >= 0) { var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data if ((sum >= 0 && val > 0) // Positive stack || (sum <= 0 && val < 0) // Negative stack ) { sum += val; stackedOver = val; break; } } } resultVal[0] = sum; resultVal[1] = stackedOver; return resultVal; }); targetData.hostModel.setData(newData); // Update for consequent calculation targetStackInfo.data = newData; }); } // TODO // ??? refactor? check the outer usage of data provider. // merge with defaultDimValueGetter? /** * If normal array used, mutable chunk size is supported. * If typed array used, chunk size must be fixed. */ function DefaultDataProvider(source, dimSize) { if (!Source.isInstance(source)) { source = Source.seriesDataToSource(source); } this._source = source; var data = this._data = source.data; var sourceFormat = source.sourceFormat; // Typed array. TODO IE10+? if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) { if (__DEV__) { if (dimSize == null) { throw new Error('Typed array data must specify dimension size'); } } this._offset = 0; this._dimSize = dimSize; this._data = data; } var methods = providerMethods[ sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + source.seriesLayoutBy : sourceFormat ]; if (__DEV__) { assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat); } extend(this, methods); } var providerProto = DefaultDataProvider.prototype; // If data is pure without style configuration providerProto.pure = false; // If data is persistent and will not be released after use. providerProto.persistent = true; // ???! FIXME legacy data provider do not has method getSource providerProto.getSource = function () { return this._source; }; var providerMethods = { 'arrayRows_column': { pure: true, count: function () { return Math.max(0, this._data.length - this._source.startIndex); }, getItem: function (idx) { return this._data[idx + this._source.startIndex]; }, appendData: appendDataSimply }, 'arrayRows_row': { pure: true, count: function () { var row = this._data[0]; return row ? Math.max(0, row.length - this._source.startIndex) : 0; }, getItem: function (idx) { idx += this._source.startIndex; var item = []; var data = this._data; for (var i = 0; i < data.length; i++) { var row = data[i]; item.push(row ? row[idx] : null); } return item; }, appendData: function () { throw new Error('Do not support appendData when set seriesLayoutBy: "row".'); } }, 'objectRows': { pure: true, count: countSimply, getItem: getItemSimply, appendData: appendDataSimply }, 'keyedColumns': { pure: true, count: function () { var dimName = this._source.dimensionsDefine[0].name; var col = this._data[dimName]; return col ? col.length : 0; }, getItem: function (idx) { var item = []; var dims = this._source.dimensionsDefine; for (var i = 0; i < dims.length; i++) { var col = this._data[dims[i].name]; item.push(col ? col[idx] : null); } return item; }, appendData: function (newData) { var data = this._data; each$1(newData, function (newCol, key) { var oldCol = data[key] || (data[key] = []); for (var i = 0; i < (newCol || []).length; i++) { oldCol.push(newCol[i]); } }); } }, 'original': { count: countSimply, getItem: getItemSimply, appendData: appendDataSimply }, 'typedArray': { persistent: false, pure: true, count: function () { return this._data ? (this._data.length / this._dimSize) : 0; }, getItem: function (idx) { idx = idx - this._offset; var item = []; var offset = this._dimSize * idx; for (var i = 0; i < this._dimSize; i++) { item[i] = this._data[offset + i]; } return item; }, appendData: function (newData) { if (__DEV__) { assert$1( isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray' ); } this._data = newData; }, // Clean self if data is already used. clean: function () { // PENDING this._offset += this.count(); this._data = null; } } }; function countSimply() { return this._data.length; } function getItemSimply(idx) { return this._data[idx]; } function appendDataSimply(newData) { for (var i = 0; i < newData.length; i++) { this._data.push(newData[i]); } } var rawValueGetters = { arrayRows: getRawValueSimply, objectRows: function (dataItem, dataIndex, dimIndex, dimName) { return dimIndex != null ? dataItem[dimName] : dataItem; }, keyedColumns: getRawValueSimply, original: function (dataItem, dataIndex, dimIndex, dimName) { // FIXME // In some case (markpoint in geo (geo-map.html)), dataItem // is {coord: [...]} var value = getDataItemValue(dataItem); return (dimIndex == null || !(value instanceof Array)) ? value : value[dimIndex]; }, typedArray: getRawValueSimply }; function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) { return dimIndex != null ? dataItem[dimIndex] : dataItem; } var defaultDimValueGetters = { arrayRows: getDimValueSimply, objectRows: function (dataItem, dimName, dataIndex, dimIndex) { return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]); }, keyedColumns: getDimValueSimply, original: function (dataItem, dimName, dataIndex, dimIndex) { // Performance sensitive, do not use modelUtil.getDataItemValue. // If dataItem is an plain object with no value field, the var `value` // will be assigned with the object, but it will be tread correctly // in the `convertDataValue`. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 } if (!this._rawData.pure && isDataItemOption(dataItem)) { this.hasItemOption = true; } return converDataValue( (value instanceof Array) ? value[dimIndex] // If value is a single number or something else not array. : value, this._dimensionInfos[dimName] ); }, typedArray: function (dataItem, dimName, dataIndex, dimIndex) { return dataItem[dimIndex]; } }; function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) { return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]); } /** * This helper method convert value in data. * @param {string|number|Date} value * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed. */ function converDataValue(value, dimInfo) { // Performance sensitive. var dimType = dimInfo && dimInfo.type; if (dimType === 'ordinal') { // If given value is a category string var ordinalMeta = dimInfo && dimInfo.ordinalMeta; return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value; } if (dimType === 'time' // spead up when using timestamp && typeof value !== 'number' && value != null && value !== '-' ) { value = +parseDate(value); } // dimType defaults 'number'. // If dimType is not ordinal and value is null or undefined or NaN or '-', // parse to NaN. return (value == null || value === '') ? NaN // If string (like '-'), using '+' parse to NaN // If object, also parse to NaN : +value; } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem, // Consider persistent. // Caution: why use raw value to display on label or tooltip? // A reason is to avoid format. For example time value we do not know // how to format is expected. More over, if stack is used, calculated // value may be 0.91000000001, which have brings trouble to display. // TODO: consider how to treat null/undefined/NaN when display? /** * @param {module:echarts/data/List} data * @param {number} dataIndex * @param {string|number} [dim] dimName or dimIndex * @return {Array.<number>|string|number} can be null/undefined. */ function retrieveRawValue(data, dataIndex, dim) { if (!data) { return; } // Consider data may be not persistent. var dataItem = data.getRawDataItem(dataIndex); if (dataItem == null) { return; } var sourceFormat = data.getProvider().getSource().sourceFormat; var dimName; var dimIndex; var dimInfo = data.getDimensionInfo(dim); if (dimInfo) { dimName = dimInfo.name; dimIndex = dimInfo.index; } return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName); } /** * Compatible with some cases (in pie, map) like: * data: [{name: 'xx', value: 5, selected: true}, ...] * where only sourceFormat is 'original' and 'objectRows' supported. * * ??? TODO * Supported detail options in data item when using 'arrayRows'. * * @param {module:echarts/data/List} data * @param {number} dataIndex * @param {string} attr like 'selected' */ function retrieveRawAttr(data, dataIndex, attr) { if (!data) { return; } var sourceFormat = data.getProvider().getSource().sourceFormat; if (sourceFormat !== SOURCE_FORMAT_ORIGINAL && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS ) { return; } var dataItem = data.getRawDataItem(dataIndex); if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) { dataItem = null; } if (dataItem) { return dataItem[attr]; } } var DIMENSION_LABEL_REG = /\{@(.+?)\}/g; // PENDING A little ugly var dataFormatMixin = { /** * Get params for formatter * @param {number} dataIndex * @param {string} [dataType] * @return {Object} */ getDataParams: function (dataIndex, dataType) { var data = this.getData(dataType); var rawValue = this.getRawValue(dataIndex, dataType); var rawDataIndex = data.getRawIndex(dataIndex); var name = data.getName(dataIndex, true); var itemOpt = data.getRawDataItem(dataIndex); var color = data.getItemVisual(dataIndex, 'color'); return { componentType: this.mainType, componentSubType: this.subType, seriesType: this.mainType === 'series' ? this.subType : null, seriesIndex: this.seriesIndex, seriesId: this.id, seriesName: this.name, name: name, dataIndex: rawDataIndex, data: itemOpt, dataType: dataType, value: rawValue, color: color, marker: getTooltipMarker(color), // Param name list for mapping `a`, `b`, `c`, `d`, `e` $vars: ['seriesName', 'name', 'value'] }; }, /** * Format label * @param {number} dataIndex * @param {string} [status='normal'] 'normal' or 'emphasis' * @param {string} [dataType] * @param {number} [dimIndex] * @param {string} [labelProp='label'] * @return {string} If not formatter, return null/undefined */ getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) { status = status || 'normal'; var data = this.getData(dataType); var itemModel = data.getItemModel(dataIndex); var params = this.getDataParams(dataIndex, dataType); if (dimIndex != null && (params.value instanceof Array)) { params.value = params.value[dimIndex]; } var formatter = itemModel.get( status === 'normal' ? [labelProp || 'label', 'formatter'] : [status, labelProp || 'label', 'formatter'] ); if (typeof formatter === 'function') { params.status = status; return formatter(params); } else if (typeof formatter === 'string') { var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'. // Do not support '}' in dim name util have to. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) { var len = dim.length; if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') { dim = +dim.slice(1, len - 1); // Also: '[]' => 0 } return retrieveRawValue(data, dataIndex, dim); }); } }, /** * Get raw value in option * @param {number} idx * @param {string} [dataType] * @return {Array|number|string} */ getRawValue: function (idx, dataType) { return retrieveRawValue(this.getData(dataType), idx); }, /** * Should be implemented. * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {number} [dataType] * @return {string} tooltip string */ formatTooltip: function () { // Empty function } }; /** * @param {Object} define * @return See the return of `createTask`. */ function createTask(define) { return new Task(define); } /** * @constructor * @param {Object} define * @param {Function} define.reset Custom reset * @param {Function} [define.plan] Returns 'reset' indicate reset immediately. * @param {Function} [define.count] count is used to determin data task. * @param {Function} [define.onDirty] count is used to determin data task. */ function Task(define) { define = define || {}; this._reset = define.reset; this._plan = define.plan; this._count = define.count; this._onDirty = define.onDirty; this._dirty = true; // Context must be specified implicitly, to // avoid miss update context when model changed. this.context; } var taskProto = Task.prototype; /** * @param {Object} performArgs * @param {number} [performArgs.step] Specified step. * @param {number} [performArgs.skip] Skip customer perform call. */ taskProto.perform = function (performArgs) { var upTask = this._upstream; var skip = performArgs && performArgs.skip; // TODO some refactor. // Pull data. Must pull data each time, because context.data // may be updated by Series.setData. if (this._dirty && upTask) { var context = this.context; context.data = context.outputData = upTask.context.outputData; } if (this.__pipeline) { this.__pipeline.currentTask = this; } var planResult; if (this._plan && !skip) { planResult = this._plan(this.context); } var forceFirstProgress; if (this._dirty || planResult === 'reset') { this._dirty = false; forceFirstProgress = reset(this, skip); } var step = performArgs && performArgs.step; if (upTask) { if (__DEV__) { assert$1(upTask._outputDueEnd != null); } // ??? FIXME move to schedueler? // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd); this._dueEnd = upTask._outputDueEnd; } // DataTask or overallTask else { if (__DEV__) { assert$1(!this._progress || this._count); } this._dueEnd = this._count ? this._count(this.context) : Infinity; } // Note: Stubs, that its host overall task let it has progress, has progress. // If no progress, pass index from upstream to downstream each time plan called. if (this._progress) { var start = this._dueIndex; var end = Math.min( step != null ? this._dueIndex + step : Infinity, this._dueEnd ); !skip && (forceFirstProgress || start < end) && ( this._progress({start: start, end: end}, this.context) ); this._dueIndex = end; // If no `outputDueEnd`, assume that output data and // input data is the same, so use `dueIndex` as `outputDueEnd`. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end; if (__DEV__) { // ??? Can not rollback. assert$1(outputDueEnd >= this._outputDueEnd); } this._outputDueEnd = outputDueEnd; } else { // (1) Some overall task has no progress. // (2) Stubs, that its host overall task do not let it has progress, has no progress. // This should always be performed so it can be passed to downstream. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd; } return this.unfinished(); }; taskProto.dirty = function () { this._dirty = true; this._onDirty && this._onDirty(this.context); }; /** * @param {Object} [params] */ function reset(taskIns, skip) { taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0; taskIns._settedOutputEnd = null; var progress; var forceFirstProgress; if (!skip && taskIns._reset) { progress = taskIns._reset(taskIns.context); if (progress && progress.progress) { forceFirstProgress = progress.forceFirstProgress; progress = progress.progress; } } taskIns._progress = progress; var downstream = taskIns._downstream; downstream && downstream.dirty(); return forceFirstProgress; } /** * @return {boolean} */ taskProto.unfinished = function () { return this._progress && this._dueIndex < this._dueEnd; }; /** * @param {Object} downTask The downstream task. * @return {Object} The downstream task. */ taskProto.pipe = function (downTask) { if (__DEV__) { assert$1(downTask && !downTask._disposed && downTask !== this); } // If already downstream, do not dirty downTask. if (this._downstream !== downTask || this._dirty) { this._downstream = downTask; downTask._upstream = this; downTask.dirty(); } }; taskProto.dispose = function () { if (this._disposed) { return; } this._upstream && (this._upstream._downstream = null); this._downstream && (this._downstream._upstream = null); this._dirty = false; this._disposed = true; }; taskProto.getUpstream = function () { return this._upstream; }; taskProto.getDownstream = function () { return this._downstream; }; taskProto.setOutputEnd = function (end) { // ??? FIXME: check // This only happend in dataTask, dataZoom, map, currently. // where dataZoom do not set end each time, but only set // when reset. So we should record the setted end, in case // that the stub of dataZoom perform again and earse the // setted end by upstream. this._outputDueEnd = this._settedOutputEnd = end; // this._outputDueEnd = end; }; /////////////////////////////////////////////////////////// // For stream debug (Should be commented out after used!) // Usage: printTask(this, 'begin'); // Usage: printTask(this, null, {someExtraProp}); // function printTask(task, prefix, extra) { // window.ecTaskUID == null && (window.ecTaskUID = 0); // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`); // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`); // var props = []; // if (task.__pipeline) { // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`; // props.push({text: 'idx', value: val}); // } else { // var stubCount = 0; // task.agentStubMap.each(() => stubCount++); // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`}); // } // props.push({text: 'uid', value: task.uidDebug}); // if (task.__pipeline) { // props.push({text: 'pid', value: task.__pipeline.id}); // task.agent && props.push( // {text: 'stubFor', value: task.agent.uidDebug} // ); // } // props.push( // {text: 'dirty', value: task._dirty}, // {text: 'dueIndex', value: task._dueIndex}, // {text: 'dueEnd', value: task._dueEnd}, // {text: 'outputDueEnd', value: task._outputDueEnd} // ); // if (extra) { // Object.keys(extra).forEach(key => { // props.push({text: key, value: extra[key]}); // }); // } // var args = ['color: blue']; // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => ( // args.push('color: black', 'color: red'), // `${item.text}: %c${item.value}` // )).join('%c, '); // console.log.apply(console, [msg].concat(args)); // // console.log(this); // } var inner$4 = makeInner(); var SeriesModel = ComponentModel.extend({ type: 'series.__base__', /** * @readOnly */ seriesIndex: 0, // coodinateSystem will be injected in the echarts/CoordinateSystem coordinateSystem: null, /** * @type {Object} * @protected */ defaultOption: null, /** * Data provided for legend * @type {Function} */ // PENDING legendDataProvider: null, /** * Access path of color for visual */ visualColorAccessPath: 'itemStyle.color', /** * Support merge layout params. * Only support 'box' now (left/right/top/bottom/width/height). * @type {string|Object} Object can be {ignoreSize: true} * @readOnly */ layoutMode: null, init: function (option, parentModel, ecModel, extraOpt) { /** * @type {number} * @readOnly */ this.seriesIndex = this.componentIndex; this.dataTask = createTask({ count: dataTaskCount, reset: dataTaskReset }); this.dataTask.context = {model: this}; this.mergeDefaultAndTheme(option, ecModel); prepareSource(this); var data = this.getInitialData(option, ecModel); wrapData(data, this); this.dataTask.context.data = data; if (__DEV__) { assert$1(data, 'getInitialData returned invalid data.'); } /** * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph} * @private */ inner$4(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make // dataBeforeProcessed by cloneShallow), cloneShallow will // cause data.graph.data !== data when using // module:echarts/data/Graph or module:echarts/data/Tree. // See module:echarts/data/helper/linkList // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model // init or merge stage, because the data can be restored. So we do not `restoreData` // and `setData` here, which forbids calling `seriesModel.getData()` in this stage. // Call `seriesModel.getRawData()` instead. // this.restoreData(); autoSeriesName(this); }, /** * Util for merge default and theme to option * @param {Object} option * @param {module:echarts/model/Global} ecModel */ mergeDefaultAndTheme: function (option, ecModel) { var layoutMode = this.layoutMode; var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme. // But if name duplicate between series subType // (for example: parallel) add component mainType, // add suffix 'Series'. var themeSubType = this.subType; if (ComponentModel.hasClass(themeSubType)) { themeSubType += 'Series'; } merge( option, ecModel.getTheme().get(this.subType) ); merge(option, this.getDefaultOption()); // Default label emphasis `show` defaultEmphasis(option, 'label', ['show']); this.fillDataTextStyle(option.data); if (layoutMode) { mergeLayoutParam(option, inputPositionParams, layoutMode); } }, mergeOption: function (newSeriesOption, ecModel) { // this.settingTask.dirty(); newSeriesOption = merge(this.option, newSeriesOption, true); this.fillDataTextStyle(newSeriesOption.data); var layoutMode = this.layoutMode; if (layoutMode) { mergeLayoutParam(this.option, newSeriesOption, layoutMode); } prepareSource(this); var data = this.getInitialData(newSeriesOption, ecModel); wrapData(data, this); this.dataTask.dirty(); this.dataTask.context.data = data; inner$4(this).dataBeforeProcessed = data; autoSeriesName(this); }, fillDataTextStyle: function (data) { // Default data label emphasis `show` // FIXME Tree structure data ? // FIXME Performance ? if (data) { var props = ['show']; for (var i = 0; i < data.length; i++) { if (data[i] && data[i].label) { defaultEmphasis(data[i], 'label', props); } } } }, /** * Init a data structure from data related option in series * Must be overwritten */ getInitialData: function () {}, /** * Append data to list * @param {Object} params * @param {Array|TypedArray} params.data */ appendData: function (params) { // FIXME ??? // (1) If data from dataset, forbidden append. // (2) support append data of dataset. var data = this.getRawData(); data.appendData(params.data); }, /** * Consider some method like `filter`, `map` need make new data, * We should make sure that `seriesModel.getData()` get correct * data in the stream procedure. So we fetch data from upstream * each time `task.perform` called. * @param {string} [dataType] * @return {module:echarts/data/List} */ getData: function (dataType) { var task = getCurrentTask(this); if (task) { var data = task.context.data; return dataType == null ? data : data.getLinkedData(dataType); } else { // When series is not alive (that may happen when click toolbox // restore or setOption with not merge mode), series data may // be still need to judge animation or something when graphic // elements want to know whether fade out. return inner$4(this).data; } }, /** * @param {module:echarts/data/List} data */ setData: function (data) { var task = getCurrentTask(this); if (task) { var context = task.context; // Consider case: filter, data sample. if (context.data !== data && task.isOverallFilter) { task.setOutputEnd(data.count()); } context.outputData = data; // Caution: setData should update context.data, // Because getData may be called multiply in a // single stage and expect to get the data just // set. (For example, AxisProxy, x y both call // getData and setDate sequentially). // So the context.data should be fetched from // upstream each time when a stage starts to be // performed. if (task !== this.dataTask) { context.data = data; } } inner$4(this).data = data; }, /** * @see {module:echarts/data/helper/sourceHelper#getSource} * @return {module:echarts/data/Source} source */ getSource: function () { return getSource(this); }, /** * Get data before processed * @return {module:echarts/data/List} */ getRawData: function () { return inner$4(this).dataBeforeProcessed; }, /** * Get base axis if has coordinate system and has axis. * By default use coordSys.getBaseAxis(); * Can be overrided for some chart. * @return {type} description */ getBaseAxis: function () { var coordSys = this.coordinateSystem; return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis(); }, // FIXME /** * Default tooltip formatter * * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {number} [dataType] */ formatTooltip: function (dataIndex, multipleSeries, dataType) { function formatArrayValue(value) { // ??? TODO refactor these logic. // check: category-no-encode-has-axis-data in dataset.html var vertially = reduce(value, function (vertially, val, idx) { var dimItem = data.getDimensionInfo(idx); return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null; }, 0); var result = []; tooltipDims.length ? each$1(tooltipDims, function (dim) { setEachItem(retrieveRawValue(data, dataIndex, dim), dim); }) // By default, all dims is used on tooltip. : each$1(value, setEachItem); function setEachItem(val, dim) { var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip. if (!dimInfo || dimInfo.otherDims.tooltip === false) { return; } var dimType = dimInfo.type; var dimHead = getTooltipMarker({color: color, type: 'subItem'}); var valStr = (vertially ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': ' : '' ) // FIXME should not format time for raw data? + encodeHTML(dimType === 'ordinal' ? val + '' : dimType === 'time' ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val)) : addCommas(val) ); valStr && result.push(valStr); } return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', '); } function formatSingleValue(val) { return encodeHTML(addCommas(val)); } var data = this.getData(); var tooltipDims = data.mapDimension('defaultedTooltip', true); var tooltipDimLen = tooltipDims.length; var value = this.getRawValue(dataIndex); var isValueArr = isArray(value); var color = data.getItemVisual(dataIndex, 'color'); if (isObject$1(color) && color.colorStops) { color = (color.colorStops[0] || {}).color; } color = color || 'transparent'; // Complicated rule for pretty tooltip. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen)) ? formatArrayValue(value) : tooltipDimLen ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0])) : formatSingleValue(isValueArr ? value[0] : value); var colorEl = getTooltipMarker(color); var name = data.getName(dataIndex); var seriesName = this.name; if (!isNameSpecified(this)) { seriesName = ''; } seriesName = seriesName ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ') : ''; return !multipleSeries ? seriesName + colorEl + (name ? encodeHTML(name) + ': ' + formattedValue : formattedValue ) : colorEl + seriesName + formattedValue; }, /** * @return {boolean} */ isAnimationEnabled: function () { if (env$1.node) { return false; } var animationEnabled = this.getShallow('animation'); if (animationEnabled) { if (this.getData().count() > this.getShallow('animationThreshold')) { animationEnabled = false; } } return animationEnabled; }, restoreData: function () { this.dataTask.dirty(); }, getColorFromPalette: function (name, scope, requestColorNum) { var ecModel = this.ecModel; // PENDING var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum); if (!color) { color = ecModel.getColorFromPalette(name, scope, requestColorNum); } return color; }, /** * Use `data.mapDimension(coordDim, true)` instead. * @deprecated */ coordDimToDataDim: function (coordDim) { return this.getRawData().mapDimension(coordDim, true); }, /** * Get progressive rendering count each step * @return {number} */ getProgressive: function () { return this.get('progressive'); }, /** * Get progressive rendering count each step * @return {number} */ getProgressiveThreshold: function () { return this.get('progressiveThreshold'); }, /** * Get data indices for show tooltip content. See tooltip. * @abstract * @param {Array.<string>|string} dim * @param {Array.<number>} value * @param {module:echarts/coord/single/SingleAxis} baseAxis * @return {Object} {dataIndices, nestestValue}. */ getAxisTooltipData: null, /** * See tooltip. * @abstract * @param {number} dataIndex * @return {Array.<number>} Point of tooltip. null/undefined can be returned. */ getTooltipPosition: null, /** * @see {module:echarts/stream/Scheduler} */ pipeTask: null, /** * Convinient for override in extended class. * @protected * @type {Function} */ preventIncremental: null, /** * @public * @readOnly * @type {Object} */ pipelineContext: null }); mixin(SeriesModel, dataFormatMixin); mixin(SeriesModel, colorPaletteMixin); /** * MUST be called after `prepareSource` called * Here we need to make auto series, especially for auto legend. But we * do not modify series.name in option to avoid side effects. */ function autoSeriesName(seriesModel) { // User specified name has higher priority, otherwise it may cause // series can not be queried unexpectedly. var name = seriesModel.name; if (!isNameSpecified(seriesModel)) { seriesModel.name = getSeriesAutoName(seriesModel) || name; } } function getSeriesAutoName(seriesModel) { var data = seriesModel.getRawData(); var dataDims = data.mapDimension('seriesName', true); var nameArr = []; each$1(dataDims, function (dataDim) { var dimInfo = data.getDimensionInfo(dataDim); dimInfo.displayName && nameArr.push(dimInfo.displayName); }); return nameArr.join(' '); } function dataTaskCount(context) { return context.model.getRawData().count(); } function dataTaskReset(context) { var seriesModel = context.model; seriesModel.setData(seriesModel.getRawData().cloneShallow()); return dataTaskProgress; } function dataTaskProgress(param, context) { // Avoid repead cloneShallow when data just created in reset. if (param.end > context.outputData.count()) { context.model.getRawData().cloneShallow(context.outputData); } } // TODO refactor function wrapData(data, seriesModel) { each$1(data.CHANGABLE_METHODS, function (methodName) { data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel)); }); } function onDataSelfChange(seriesModel) { var task = getCurrentTask(seriesModel); if (task) { // Consider case: filter, selectRange task.setOutputEnd(this.count()); } } function getCurrentTask(seriesModel) { var scheduler = (seriesModel.ecModel || {}).scheduler; var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid); if (pipeline) { // When pipline finished, the currrentTask keep the last // task (renderTask). var task = pipeline.currentTask; if (task) { var agentStubMap = task.agentStubMap; if (agentStubMap) { task = agentStubMap.get(seriesModel.uid); } } return task; } } var Component = function () { /** * @type {module:zrender/container/Group} * @readOnly */ this.group = new Group(); /** * @type {string} * @readOnly */ this.uid = getUID('viewComponent'); }; Component.prototype = { constructor: Component, init: function (ecModel, api) {}, render: function (componentModel, ecModel, api, payload) {}, dispose: function () {} }; var componentProto = Component.prototype; componentProto.updateView = componentProto.updateLayout = componentProto.updateVisual = function (seriesModel, ecModel, api, payload) { // Do nothing; }; // Enable Component.extend. enableClassExtend(Component); // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on. enableClassManagement(Component, {registerWhenExtend: true}); /** * @return {string} If large mode changed, return string 'reset'; */ var createRenderPlanner = function () { var inner = makeInner(); return function (seriesModel) { var fields = inner(seriesModel); var pipelineContext = seriesModel.pipelineContext; var originalLarge = fields.large; var originalProgressive = fields.canProgressiveRender; var large = fields.large = pipelineContext.large; var progressive = fields.canProgressiveRender = pipelineContext.canProgressiveRender; return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset'; }; }; var inner$5 = makeInner(); var renderPlanner = createRenderPlanner(); function Chart() { /** * @type {module:zrender/container/Group} * @readOnly */ this.group = new Group(); /** * @type {string} * @readOnly */ this.uid = getUID('viewChart'); this.renderTask = createTask({ plan: renderTaskPlan, reset: renderTaskReset }); this.renderTask.context = {view: this}; } Chart.prototype = { type: 'chart', /** * Init the chart. * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ init: function (ecModel, api) {}, /** * Render the chart. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ render: function (seriesModel, ecModel, api, payload) {}, /** * Highlight series or specified data item. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ highlight: function (seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'emphasis'); }, /** * Downplay series or specified data item. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ downplay: function (seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'normal'); }, /** * Remove self. * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ remove: function (ecModel, api) { this.group.removeAll(); }, /** * Dispose self. * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ dispose: function () {}, /** * Rendering preparation in progressive mode. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ incrementalPrepareRender: null, /** * Render in progressive mode. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ incrementalRender: null, /** * Update transform directly. * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload * @return {Object} {update: true} */ updateTransform: null /** * The view contains the given point. * @interface * @param {Array.<number>} point * @return {boolean} */ // containPoint: function () {} }; var chartProto = Chart.prototype; chartProto.updateView = chartProto.updateLayout = chartProto.updateVisual = function (seriesModel, ecModel, api, payload) { this.render(seriesModel, ecModel, api, payload); }; /** * Set state of single element * @param {module:zrender/Element} el * @param {string} state */ function elSetState(el, state) { if (el) { el.trigger(state); if (el.type === 'group') { for (var i = 0; i < el.childCount(); i++) { elSetState(el.childAt(i), state); } } } } /** * @param {module:echarts/data/List} data * @param {Object} payload * @param {string} state 'normal'|'emphasis' */ function toggleHighlight(data, payload, state) { var dataIndex = queryDataIndex(data, payload); if (dataIndex != null) { each$1(normalizeToArray(dataIndex), function (dataIdx) { elSetState(data.getItemGraphicEl(dataIdx), state); }); } else { data.eachItemGraphicEl(function (el) { elSetState(el, state); }); } } // Enable Chart.extend. enableClassExtend(Chart, ['dispose']); // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on. enableClassManagement(Chart, {registerWhenExtend: true}); Chart.markUpdateMethod = function (payload, methodName) { inner$5(payload).updateMethod = methodName; }; function renderTaskPlan(context) { return renderPlanner(context.model); } function renderTaskReset(context) { var seriesModel = context.model; var ecModel = context.ecModel; var api = context.api; var payload = context.payload; // ???! remove updateView updateVisual var canProgressiveRender = seriesModel.pipelineContext.canProgressiveRender; var view = context.view; var updateMethod = payload && inner$5(payload).updateMethod; var methodName = canProgressiveRender ? 'incrementalPrepareRender' : (updateMethod && view[updateMethod]) ? updateMethod // `appendData` is also supported when data amount // is less than progressive threshold. : 'render'; if (methodName !== 'render') { view[methodName](seriesModel, ecModel, api, payload); } return progressMethodMap[methodName]; } var progressMethodMap = { incrementalPrepareRender: { progress: function (params, context) { context.view.incrementalRender( params, context.model, context.ecModel, context.api, context.payload ); } }, render: { // Put view.render in `progress` to support appendData. But in this case // view.render should not be called in reset, otherwise it will be called // twise. Use `forceFirstProgress` to make sure that view.render is called // in any cases. forceFirstProgress: true, progress: function (params, context) { context.view.render( context.model, context.ecModel, context.api, context.payload ); } } }; /** * @public * @param {(Function)} fn * @param {number} [delay=0] Unit: ms. * @param {boolean} [debounce=false] * true: If call interval less than `delay`, only the last call works. * false: If call interval less than `delay, call works on fixed rate. * @return {(Function)} throttled fn. */ function throttle(fn, delay, debounce) { var currCall; var lastCall = 0; var lastExec = 0; var timer = null; var diff; var scope; var args; var debounceNextCall; delay = delay || 0; function exec() { lastExec = (new Date()).getTime(); timer = null; fn.apply(scope, args || []); } var cb = function () { currCall = (new Date()).getTime(); scope = this; args = arguments; var thisDelay = debounceNextCall || delay; var thisDebounce = debounceNextCall || debounce; debounceNextCall = null; diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay; clearTimeout(timer); if (thisDebounce) { timer = setTimeout(exec, thisDelay); } else { if (diff >= 0) { exec(); } else { timer = setTimeout(exec, -diff); } } lastCall = currCall; }; /** * Clear throttle. * @public */ cb.clear = function () { if (timer) { clearTimeout(timer); timer = null; } }; /** * Enable debounce once. */ cb.debounceNextCall = function (debounceDelay) { debounceNextCall = debounceDelay; }; return cb; } /** * Create throttle method or update throttle rate. * * @example * ComponentView.prototype.render = function () { * ... * throttle.createOrUpdate( * this, * '_dispatchAction', * this.model.get('throttle'), * 'fixRate' * ); * }; * ComponentView.prototype.remove = function () { * throttle.clear(this, '_dispatchAction'); * }; * ComponentView.prototype.dispose = function () { * throttle.clear(this, '_dispatchAction'); * }; * * @public * @param {Object} obj * @param {string} fnAttr * @param {number} [rate] * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce' * @return {Function} throttled function. */ /** * Clear throttle. Example see throttle.createOrUpdate. * * @public * @param {Object} obj * @param {string} fnAttr */ var seriesColor = { createOnAllSeries: true, performRawSeries: true, reset: function (seriesModel, ecModel) { var data = seriesModel.getData(); var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.'); var color = seriesModel.get(colorAccessPath) // Set in itemStyle || seriesModel.getColorFromPalette( // TODO series count changed. seriesModel.name, null, ecModel.getSeriesCount() ); // Default color // FIXME Set color function or use the platte color data.setVisual('color', color); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { if (typeof color === 'function' && !(color instanceof Gradient)) { data.each(function (idx) { data.setItemVisual( idx, 'color', color(seriesModel.getDataParams(idx)) ); }); } // itemStyle in each data item var dataEach = function (data, idx) { var itemModel = data.getItemModel(idx); var color = itemModel.get(colorAccessPath, true); if (color != null) { data.setItemVisual(idx, 'color', color); } }; return { dataEach: data.hasItemOption ? dataEach : null }; } } }; var lang = { toolbox: { brush: { title: { rect: '矩形选择', polygon: '圈选', lineX: '横向选择', lineY: '纵向选择', keep: '保持选择', clear: '清除选择' } }, dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] }, dataZoom: { title: { zoom: '区域缩放', back: '区域缩放还原' } }, magicType: { title: { line: '切换为折线图', bar: '切换为柱状图', stack: '切换为堆叠', tiled: '切换为平铺' } }, restore: { title: '还原' }, saveAsImage: { title: '保存为图片', lang: ['右键另存为图片'] } }, series: { typeNames: { pie: '饼图', bar: '柱状图', line: '折线图', scatter: '散点图', effectScatter: '涟漪散点图', radar: '雷达图', tree: '树图', treemap: '矩形树图', boxplot: '箱型图', candlestick: 'K线图', k: 'K线图', heatmap: '热力图', map: '地图', parallel: '平行坐标图', lines: '线图', graph: '关系图', sankey: '桑基图', funnel: '漏斗图', gauge: '仪表盘图', pictorialBar: '象形柱图', themeRiver: '主题河流图', sunburst: '旭日图' } }, aria: { general: { withTitle: '这是一个关于“{title}”的图表。', withoutTitle: '这是一个图表,' }, series: { single: { prefix: '', withName: '图表类型是{seriesType},表示{seriesName}。', withoutName: '图表类型是{seriesType}。' }, multiple: { prefix: '它由{seriesCount}个图表系列组成。', withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},', withoutName: '第{seriesId}个系列是一个{seriesType},', separator: { middle: ';', end: '。' } } }, data: { allData: '其数据是——', partialData: '其中,前{displayCnt}项是——', withName: '{name}的数据是{value}', withoutName: '{value}', separator: { middle: ',', end: '' } } } }; var aria = function (dom, ecModel) { var ariaModel = ecModel.getModel('aria'); if (!ariaModel.get('show')) { return; } else if (ariaModel.get('description')) { dom.setAttribute('aria-label', ariaModel.get('description')); return; } var seriesCnt = 0; ecModel.eachSeries(function (seriesModel, idx) { ++seriesCnt; }, this); var maxDataCnt = ariaModel.get('data.maxCount') || 10; var maxSeriesCnt = ariaModel.get('series.maxCount') || 10; var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt); var ariaLabel; if (seriesCnt < 1) { // No series, no aria label return; } else { var title = getTitle(); if (title) { ariaLabel = replace(getConfig('general.withTitle'), { title: title }); } else { ariaLabel = getConfig('general.withoutTitle'); } var seriesLabels = []; var prefix = seriesCnt > 1 ? 'series.multiple.prefix' : 'series.single.prefix'; ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt }); ecModel.eachSeries(function (seriesModel, idx) { if (idx < displaySeriesCnt) { var seriesLabel; var seriesName = seriesModel.get('name'); var seriesTpl = 'series.' + (seriesCnt > 1 ? 'multiple' : 'single') + '.'; seriesLabel = getConfig(seriesName ? seriesTpl + 'withName' : seriesTpl + 'withoutName'); seriesLabel = replace(seriesLabel, { seriesId: seriesModel.seriesIndex, seriesName: seriesModel.get('name'), seriesType: getSeriesTypeName(seriesModel.subType) }); var data = seriesModel.getData(); window.data = data; if (data.count() > maxDataCnt) { // Show part of data seriesLabel += replace(getConfig('data.partialData'), { displayCnt: maxDataCnt }); } else { seriesLabel += getConfig('data.allData'); } var dataLabels = []; for (var i = 0; i < data.count(); i++) { if (i < maxDataCnt) { var name = data.getName(i); var value = retrieveRawValue(data, i); dataLabels.push( replace( name ? getConfig('data.withName') : getConfig('data.withoutName'), { name: name, value: value } ) ); } } seriesLabel += dataLabels .join(getConfig('data.separator.middle')) + getConfig('data.separator.end'); seriesLabels.push(seriesLabel); } }); ariaLabel += seriesLabels .join(getConfig('series.multiple.separator.middle')) + getConfig('series.multiple.separator.end'); dom.setAttribute('aria-label', ariaLabel); } function replace(str, keyValues) { if (typeof str !== 'string') { return str; } var result = str; each$1(keyValues, function (value, key) { result = result.replace( new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value ); }); return result; } function getConfig(path) { var userConfig = ariaModel.get(path); if (userConfig == null) { var pathArr = path.split('.'); var result = lang.aria; for (var i = 0; i < pathArr.length; ++i) { result = result[pathArr[i]]; } return result; } else { return userConfig; } } function getTitle() { var title = ecModel.getModel('title').option; if (title && title.length) { title = title[0]; } return title && title.text; } function getSeriesTypeName(type) { return lang.series.typeNames[type] || '自定义图'; } }; var PI$1 = Math.PI; /** * @param {module:echarts/ExtensionAPI} api * @param {Object} [opts] * @param {string} [opts.text] * @param {string} [opts.color] * @param {string} [opts.textColor] * @return {module:zrender/Element} */ var loadingDefault = function (api, opts) { opts = opts || {}; defaults(opts, { text: 'loading', color: '#c23531', textColor: '#000', maskColor: 'rgba(255, 255, 255, 0.8)', zlevel: 0 }); var mask = new Rect({ style: { fill: opts.maskColor }, zlevel: opts.zlevel, z: 10000 }); var arc = new Arc({ shape: { startAngle: -PI$1 / 2, endAngle: -PI$1 / 2 + 0.1, r: 10 }, style: { stroke: opts.color, lineCap: 'round', lineWidth: 5 }, zlevel: opts.zlevel, z: 10001 }); var labelRect = new Rect({ style: { fill: 'none', text: opts.text, textPosition: 'right', textDistance: 10, textFill: opts.textColor }, zlevel: opts.zlevel, z: 10001 }); arc.animateShape(true) .when(1000, { endAngle: PI$1 * 3 / 2 }) .start('circularInOut'); arc.animateShape(true) .when(1000, { startAngle: PI$1 * 3 / 2 }) .delay(300) .start('circularInOut'); var group = new Group(); group.add(arc); group.add(labelRect); group.add(mask); // Inject resize group.resize = function () { var cx = api.getWidth() / 2; var cy = api.getHeight() / 2; arc.setShape({ cx: cx, cy: cy }); var r = arc.shape.r; labelRect.setShape({ x: cx - r, y: cy - r, width: r * 2, height: r * 2 }); mask.setShape({ x: 0, y: 0, width: api.getWidth(), height: api.getHeight() }); }; group.resize(); return group; }; /** * @module echarts/stream/Scheduler */ /** * @constructor */ function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) { // this._pipelineMap = createHashMap(); this.ecInstance = ecInstance; this.api = api; this.unfinished; // Fix current processors in case that in some rear cases that // processors might be registered after echarts instance created. // Register processors incrementally for a echarts instance is // not supported by this stream architecture. this._dataProcessorHandlers = dataProcessorHandlers.slice(); this._visualHandlers = visualHandlers.slice(); /** * @private * @type { * [handlerUID: string]: { * seriesTaskMap?: { * [seriesUID: string]: Task * }, * overallTask?: Task * } * } */ this._stageTaskMap = createHashMap(); } var proto = Scheduler.prototype; // If seriesModel provided, incremental threshold is check by series data. proto.getPerformArgs = function (task, isBlock) { // For overall task if (!task.__pipeline) { return; } var pipeline = this._pipelineMap.get(task.__pipeline.id); var pCtx = pipeline.context; var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.canProgressiveRender) && task.__idxInPipeline > pipeline.bockIndex; return {step: incremental ? pipeline.step : null}; }; proto.getPipeline = function (pipelineId) { return this._pipelineMap.get(pipelineId); }; /** * Current, progressive rendering starts from visual and layout. * Always detect render mode in the same stage, avoiding that incorrect * detection caused by data filtering. * Caution: * `updateStreamModes` use `seriesModel.getData()`. */ proto.updateStreamModes = function (seriesModel, view) { var pipeline = this._pipelineMap.get(seriesModel.uid); var data = seriesModel.getData(); var dataLen = data.count(); // `canProgressiveRender` means that can render progressively in each // animation frame. Note that some types of series do not provide // `view.incrementalPrepareRender` but support `chart.appendData`. We // use the term `incremental` but not `progressive` to describe the // case that `chart.appendData`. var canProgressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold; var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); seriesModel.pipelineContext = pipeline.context = { canProgressiveRender: canProgressiveRender, large: large }; }; proto.restorePipelines = function (ecModel) { var scheduler = this; var pipelineMap = scheduler._pipelineMap = createHashMap(); ecModel.eachSeries(function (seriesModel) { var progressive = seriesModel.getProgressive(); var pipelineId = seriesModel.uid; pipelineMap.set(pipelineId, { id: pipelineId, head: null, tail: null, threshold: seriesModel.getProgressiveThreshold(), progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()), bockIndex: -1, step: progressive || 700, // ??? Temporarily number count: 0 }); pipe(scheduler, seriesModel, seriesModel.dataTask); }); }; proto.prepareStageTasks = function () { var stageTaskMap = this._stageTaskMap; var ecModel = this.ecInstance.getModel(); var api = this.api; each$1([this._dataProcessorHandlers, this._visualHandlers], function (stageHandlers) { each$1(stageHandlers, function (handler) { var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []); handler.reset && createSeriesStageTask(this, handler, record, ecModel, api); handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api); }, this); }, this); }; proto.prepareView = function (view, model, ecModel, api) { var renderTask = view.renderTask; var context = renderTask.context; context.model = model; context.ecModel = ecModel; context.api = api; renderTask.__block = !view.incrementalPrepareRender; pipe(this, model, renderTask); }; proto.performDataProcessorTasks = function (ecModel, payload) { // If we do not use `block` here, it should be considered when to update modes. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true}); }; // opt // opt.visualType: 'visual' or 'layout' // opt.setDirty proto.performVisualTasks = function (ecModel, payload, opt) { performStageTasks(this, this._visualHandlers, ecModel, payload, opt); }; function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) { opt = opt || {}; var unfinished; each$1(stageHandlers, function (stageHandler, idx) { if (opt.visualType && opt.visualType !== stageHandler.visualType) { return; } var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid); var seriesTaskMap = stageHandlerRecord.seriesTaskMap; var overallTask = stageHandlerRecord.overallTask; if (overallTask) { var overallNeedDirty; var agentStubMap = overallTask.agentStubMap; agentStubMap.each(function (stub) { if (needSetDirty(opt, stub)) { stub.dirty(); overallNeedDirty = true; } }); overallNeedDirty && overallTask.dirty(); updatePayload(overallTask, payload); var performArgs = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty, // then execute the overall task. And stub will call seriesModel.setData, // which ensures that in the overallTask seriesModel.getData() will not // return incorrect data. agentStubMap.each(function (stub) { stub.perform(performArgs); }); unfinished |= overallTask.perform(performArgs); } else if (seriesTaskMap) { seriesTaskMap.each(function (task, pipelineId) { if (needSetDirty(opt, task)) { task.dirty(); } var performArgs = scheduler.getPerformArgs(task, opt.block); performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model); updatePayload(task, payload); unfinished |= task.perform(performArgs); }); } }); function needSetDirty(opt, task) { return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id)); } scheduler.unfinished |= unfinished; } proto.performSeriesTasks = function (ecModel) { var unfinished; ecModel.eachSeries(function (seriesModel) { // Progress to the end for dataInit and dataRestore. unfinished |= seriesModel.dataTask.perform(); }); this.unfinished |= unfinished; }; proto.plan = function () { // Travel pipelines, check block. this._pipelineMap.each(function (pipeline) { var task = pipeline.tail; do { if (task.__block) { pipeline.bockIndex = task.__idxInPipeline; break; } task = task.getUpstream(); } while (task); }); }; var updatePayload = proto.updatePayload = function (task, payload) { payload !== 'remain' && (task.context.payload = payload); }; function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) { var seriesTaskMap = stageHandlerRecord.seriesTaskMap || (stageHandlerRecord.seriesTaskMap = createHashMap()); var seriesType = stageHandler.seriesType; var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily, // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`, // it works but it may cause other irrelevant charts blocked. if (stageHandler.createOnAllSeries) { ecModel.eachRawSeries(create); } else if (seriesType) { ecModel.eachRawSeriesByType(seriesType, create); } else if (getTargetSeries) { getTargetSeries(ecModel, api).each(create); } function create(seriesModel) { var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once. // Reuse original task instance. var task = seriesTaskMap.get(pipelineId) || seriesTaskMap.set(pipelineId, createTask({ plan: seriesTaskPlan, reset: seriesTaskReset, count: seriesTaskCount })); task.context = { model: seriesModel, ecModel: ecModel, api: api, useClearVisual: stageHandler.isVisual && !stageHandler.isLayout, plan: stageHandler.plan, reset: stageHandler.reset, scheduler: scheduler }; pipe(scheduler, seriesModel, task); } // Clear unused series tasks. var pipelineMap = scheduler._pipelineMap; seriesTaskMap.each(function (task, pipelineId) { if (!pipelineMap.get(pipelineId)) { task.dispose(); seriesTaskMap.removeKey(pipelineId); } }); } function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) { var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage. || createTask({reset: overallTaskReset}); overallTask.context = { ecModel: ecModel, api: api, overallReset: stageHandler.overallReset, scheduler: scheduler }; // Reuse orignal stubs. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap(); var seriesType = stageHandler.seriesType; var getTargetSeries = stageHandler.getTargetSeries; var overallProgress = true; var isOverallFilter = stageHandler.isOverallFilter; // An overall task with seriesType detected or has `getTargetSeries`, we add // stub in each pipelines, it will set the overall task dirty when the pipeline // progress. Moreover, to avoid call the overall task each frame (too frequent), // we set the pipeline block. if (seriesType) { ecModel.eachRawSeriesByType(seriesType, createStub); } else if (getTargetSeries) { getTargetSeries(ecModel, api).each(createStub); } // Otherwise, (usually it is legancy case), the overall task will only be // executed when upstream dirty. Otherwise the progressive rendering of all // pipelines will be disabled unexpectedly. But it still needs stubs to receive // dirty info from upsteam. else { overallProgress = false; each$1(ecModel.getSeries(), createStub); } function createStub(seriesModel) { var pipelineId = seriesModel.uid; var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask( {reset: stubReset, onDirty: stubOnDirty} )); stub.context = { model: seriesModel, overallProgress: overallProgress, isOverallFilter: isOverallFilter }; stub.agent = overallTask; stub.__block = overallProgress; pipe(scheduler, seriesModel, stub); } // Clear unused stubs. var pipelineMap = scheduler._pipelineMap; agentStubMap.each(function (stub, pipelineId) { if (!pipelineMap.get(pipelineId)) { stub.dispose(); agentStubMap.removeKey(pipelineId); } }); } function overallTaskReset(context) { context.overallReset( context.ecModel, context.api, context.payload ); } function stubReset(context, upstreamContext) { return context.overallProgress && stubProgress; } function stubProgress() { this.agent.dirty(); this.getDownstream().dirty(); } function stubOnDirty() { this.agent && this.agent.dirty(); } function seriesTaskPlan(context) { return context.plan && context.plan( context.model, context.ecModel, context.api, context.payload ); } function seriesTaskReset(context) { if (context.useClearVisual) { context.data.clearAllVisual(); } var resetDefines = context.resetDefines = normalizeToArray(context.reset( context.model, context.ecModel, context.api, context.payload )); if (resetDefines.length) { return seriesTaskProgress; } } function seriesTaskProgress(params, context) { var data = context.data; var resetDefines = context.resetDefines; for (var k = 0; k < resetDefines.length; k++) { var resetDefine = resetDefines[k]; if (resetDefine && resetDefine.dataEach) { for (var i = params.start; i < params.end; i++) { resetDefine.dataEach(data, i); } } else if (resetDefine && resetDefine.progress) { resetDefine.progress(params, data); } } } function seriesTaskCount(context) { return context.data.count(); } function pipe(scheduler, seriesModel, task) { var pipelineId = seriesModel.uid; var pipeline = scheduler._pipelineMap.get(pipelineId); !pipeline.head && (pipeline.head = task); pipeline.tail && pipeline.tail.pipe(task); pipeline.tail = task; task.__idxInPipeline = pipeline.count++; task.__pipeline = pipeline; } Scheduler.wrapStageHandler = function (stageHandler, visualType) { if (isFunction$1(stageHandler)) { stageHandler = { overallReset: stageHandler, seriesType: detectSeriseType(stageHandler) }; } stageHandler.uid = getUID('stageHandler'); visualType && (stageHandler.visualType = visualType); return stageHandler; }; /** * Only some legacy stage handlers (usually in echarts extensions) are pure function. * To ensure that they can work normally, they should work in block mode, that is, * they should not be started util the previous tasks finished. So they cause the * progressive rendering disabled. We try to detect the series type, to narrow down * the block range to only the series type they concern, but not all series. */ function detectSeriseType(legacyFunc) { seriesType = null; try { // Assume there is no async when calling `eachSeriesByType`. legacyFunc(ecModelMock, apiMock); } catch (e) { } return seriesType; } var ecModelMock = {}; var apiMock = {}; var seriesType; mockMethods(ecModelMock, GlobalModel); mockMethods(apiMock, ExtensionAPI); ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) { seriesType = type; }; ecModelMock.eachComponent = function (cond) { if (cond.mainType === 'series' && cond.subType) { seriesType = cond.subType; } }; function mockMethods(target, Clz) { for (var name in Clz.prototype) { // Do not use hasOwnProperty target[name] = noop; } } var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF']; var lightTheme = { color: colorAll, colorLayer: [ ['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll ] }; var contrastColor = '#eee'; var axisCommon = function () { return { axisLine: { lineStyle: { color: contrastColor } }, axisTick: { lineStyle: { color: contrastColor } }, axisLabel: { textStyle: { color: contrastColor } }, splitLine: { lineStyle: { type: 'dashed', color: '#aaa' } }, splitArea: { areaStyle: { color: contrastColor } } }; }; var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42']; var theme = { color: colorPalette, backgroundColor: '#333', tooltip: { axisPointer: { lineStyle: { color: contrastColor }, crossStyle: { color: contrastColor } } }, legend: { textStyle: { color: contrastColor } }, textStyle: { color: contrastColor }, title: { textStyle: { color: contrastColor } }, toolbox: { iconStyle: { normal: { borderColor: contrastColor } } }, dataZoom: { textStyle: { color: contrastColor } }, visualMap: { textStyle: { color: contrastColor } }, timeline: { lineStyle: { color: contrastColor }, itemStyle: { normal: { color: colorPalette[1] } }, label: { normal: { textStyle: { color: contrastColor } } }, controlStyle: { normal: { color: contrastColor, borderColor: contrastColor } } }, timeAxis: axisCommon(), logAxis: axisCommon(), valueAxis: axisCommon(), categoryAxis: axisCommon(), line: { symbol: 'circle' }, graph: { color: colorPalette }, gauge: { title: { textStyle: { color: contrastColor } } }, candlestick: { itemStyle: { normal: { color: '#FD1050', color0: '#0CF49B', borderColor: '#FD1050', borderColor0: '#0CF49B' } } } }; theme.categoryAxis.splitLine.show = false; /*! * ECharts, a free, powerful charting and visualization library. * * Copyright (c) 2017, Baidu Inc. * All rights reserved. * * LICENSE * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt */ var assert = assert$1; var each = each$1; var isFunction = isFunction$1; var isObject = isObject$1; var parseClassType = ComponentModel.parseClassType; var version = '4.0.4'; var dependencies = { zrender: '4.0.3' }; var TEST_FRAME_REMAIN_TIME = 1; var PRIORITY_PROCESSOR_FILTER = 1000; var PRIORITY_PROCESSOR_STATISTIC = 5000; var PRIORITY_VISUAL_LAYOUT = 1000; var PRIORITY_VISUAL_GLOBAL = 2000; var PRIORITY_VISUAL_CHART = 3000; var PRIORITY_VISUAL_COMPONENT = 4000; // FIXME // necessary? var PRIORITY_VISUAL_BRUSH = 5000; var PRIORITY = { PROCESSOR: { FILTER: PRIORITY_PROCESSOR_FILTER, STATISTIC: PRIORITY_PROCESSOR_STATISTIC }, VISUAL: { LAYOUT: PRIORITY_VISUAL_LAYOUT, GLOBAL: PRIORITY_VISUAL_GLOBAL, CHART: PRIORITY_VISUAL_CHART, COMPONENT: PRIORITY_VISUAL_COMPONENT, BRUSH: PRIORITY_VISUAL_BRUSH } }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`, // where they must not be invoked nestedly, except the only case: invoke // dispatchAction with updateMethod "none" in main process. // This flag is used to carry out this rule. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]). var IN_MAIN_PROCESS = '__flagInMainProcess'; var OPTION_UPDATED = '__optionUpdated'; var ACTION_REG = /^[a-zA-Z0-9_]+$/; function createRegisterEventWithLowercaseName(method) { return function (eventName, handler, context) { // Event name is all lowercase eventName = eventName && eventName.toLowerCase(); Eventful.prototype[method].call(this, eventName, handler, context); }; } /** * @module echarts~MessageCenter */ function MessageCenter() { Eventful.call(this); } MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on'); MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off'); MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one'); mixin(MessageCenter, Eventful); /** * @module echarts~ECharts */ function ECharts(dom, theme$$1, opts) { opts = opts || {}; // Get theme by name if (typeof theme$$1 === 'string') { theme$$1 = themeStorage[theme$$1]; } /** * @type {string} */ this.id; /** * Group id * @type {string} */ this.group; /** * @type {HTMLElement} * @private */ this._dom = dom; var defaultRenderer = 'canvas'; if (__DEV__) { defaultRenderer = ( typeof window === 'undefined' ? global : window ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer; } /** * @type {module:zrender/ZRender} * @private */ var zr = this._zr = init$1(dom, { renderer: opts.renderer || defaultRenderer, devicePixelRatio: opts.devicePixelRatio, width: opts.width, height: opts.height }); /** * Expect 60 pfs. * @type {Function} * @private */ this._throttledZrFlush = throttle(bind(zr.flush, zr), 17); var theme$$1 = clone(theme$$1); theme$$1 && backwardCompat(theme$$1, true); /** * @type {Object} * @private */ this._theme = theme$$1; /** * @type {Array.<module:echarts/view/Chart>} * @private */ this._chartsViews = []; /** * @type {Object.<string, module:echarts/view/Chart>} * @private */ this._chartsMap = {}; /** * @type {Array.<module:echarts/view/Component>} * @private */ this._componentsViews = []; /** * @type {Object.<string, module:echarts/view/Component>} * @private */ this._componentsMap = {}; /** * @type {module:echarts/CoordinateSystem} * @private */ this._coordSysMgr = new CoordinateSystemManager(); /** * @type {module:echarts/ExtensionAPI} * @private */ var api = this._api = createExtensionAPI(this); // Sort on demand function prioritySortFunc(a, b) { return a.__prio - b.__prio; } sort(visualFuncs, prioritySortFunc); sort(dataProcessorFuncs, prioritySortFunc); /** * @type {module:echarts/stream/Scheduler} */ this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs); Eventful.call(this); /** * @type {module:echarts~MessageCenter} * @private */ this._messageCenter = new MessageCenter(); // Init mouse events this._initEvents(); // In case some people write `window.onresize = chart.resize` this.resize = bind(this.resize, this); // Can't dispatch action during rendering procedure this._pendingActions = []; zr.animation.on('frame', this._onframe, this); bindRenderedEvent(zr, this); // ECharts instance can be used as value. setAsPrimitive(this); } var echartsProto = ECharts.prototype; echartsProto._onframe = function () { if (this._disposed) { return; } var scheduler = this._scheduler; // Lazy update if (this[OPTION_UPDATED]) { var silent = this[OPTION_UPDATED].silent; this[IN_MAIN_PROCESS] = true; prepare(this); updateMethods.update.call(this); this[IN_MAIN_PROCESS] = false; this[OPTION_UPDATED] = false; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); } // Avoid do both lazy update and progress in one frame. else if (scheduler.unfinished) { // Stream progress. var remainTime = TEST_FRAME_REMAIN_TIME; var ecModel = this._model; var api = this._api; scheduler.unfinished = false; do { var startTime = +new Date(); scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold. scheduler.performDataProcessorTasks(ecModel); updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in // each frame is not a good user experience. So we follow the rule that // the extent of the coordinate system is determin in the first frame (the // frame is executed immedietely after task reset. // this._coordSysMgr.update(ecModel, api); // console.log('--- ec frame visual ---', remainTime); scheduler.performVisualTasks(ecModel); renderSeries(this, this._model, api, 'remain'); remainTime -= (+new Date() - startTime); } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event. if (!scheduler.unfinished) { this._zr.flush(); } // Else, zr flushing be ensue within the same frame, // because zr flushing is after onframe event. } }; /** * @return {HTMLElement} */ echartsProto.getDom = function () { return this._dom; }; /** * @return {module:zrender~ZRender} */ echartsProto.getZr = function () { return this._zr; }; /** * Usage: * chart.setOption(option, notMerge, lazyUpdate); * chart.setOption(option, { * notMerge: ..., * lazyUpdate: ..., * silent: ... * }); * * @param {Object} option * @param {Object|boolean} [opts] opts or notMerge. * @param {boolean} [opts.notMerge=false] * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently. */ echartsProto.setOption = function (option, notMerge, lazyUpdate) { if (__DEV__) { assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.'); } var silent; if (isObject(notMerge)) { lazyUpdate = notMerge.lazyUpdate; silent = notMerge.silent; notMerge = notMerge.notMerge; } this[IN_MAIN_PROCESS] = true; if (!this._model || notMerge) { var optionManager = new OptionManager(this._api); var theme$$1 = this._theme; var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager); ecModel.scheduler = this._scheduler; ecModel.init(null, null, theme$$1, optionManager); } this._model.setOption(option, optionPreprocessorFuncs); if (lazyUpdate) { this[OPTION_UPDATED] = {silent: silent}; this[IN_MAIN_PROCESS] = false; } else { prepare(this); updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be // fetched after `setOption`. this._zr.flush(); this[OPTION_UPDATED] = false; this[IN_MAIN_PROCESS] = false; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); } }; /** * @DEPRECATED */ echartsProto.setTheme = function () { console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0'); }; /** * @return {module:echarts/model/Global} */ echartsProto.getModel = function () { return this._model; }; /** * @return {Object} */ echartsProto.getOption = function () { return this._model && this._model.getOption(); }; /** * @return {number} */ echartsProto.getWidth = function () { return this._zr.getWidth(); }; /** * @return {number} */ echartsProto.getHeight = function () { return this._zr.getHeight(); }; /** * @return {number} */ echartsProto.getDevicePixelRatio = function () { return this._zr.painter.dpr || window.devicePixelRatio || 1; }; /** * Get canvas which has all thing rendered * @param {Object} opts * @param {string} [opts.backgroundColor] * @return {string} */ echartsProto.getRenderedCanvas = function (opts) { if (!env$1.canvasSupported) { return; } opts = opts || {}; opts.pixelRatio = opts.pixelRatio || 1; opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor'); var zr = this._zr; // var list = zr.storage.getDisplayList(); // Stop animations // Never works before in init animation, so remove it. // zrUtil.each(list, function (el) { // el.stopAnimation(true); // }); return zr.painter.getRenderedCanvas(opts); }; /** * Get svg data url * @return {string} */ echartsProto.getSvgDataUrl = function () { if (!env$1.svgSupported) { return; } var zr = this._zr; var list = zr.storage.getDisplayList(); // Stop animations each$1(list, function (el) { el.stopAnimation(true); }); return zr.painter.pathToDataUrl(); }; /** * @return {string} * @param {Object} opts * @param {string} [opts.type='png'] * @param {string} [opts.pixelRatio=1] * @param {string} [opts.backgroundColor] * @param {string} [opts.excludeComponents] */ echartsProto.getDataURL = function (opts) { opts = opts || {}; var excludeComponents = opts.excludeComponents; var ecModel = this._model; var excludesComponentViews = []; var self = this; each(excludeComponents, function (componentType) { ecModel.eachComponent({ mainType: componentType }, function (component) { var view = self._componentsMap[component.__viewId]; if (!view.group.ignore) { excludesComponentViews.push(view); view.group.ignore = true; } }); }); var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataUrl() : this.getRenderedCanvas(opts).toDataURL( 'image/' + (opts && opts.type || 'png') ); each(excludesComponentViews, function (view) { view.group.ignore = false; }); return url; }; /** * @return {string} * @param {Object} opts * @param {string} [opts.type='png'] * @param {string} [opts.pixelRatio=1] * @param {string} [opts.backgroundColor] */ echartsProto.getConnectedDataURL = function (opts) { if (!env$1.canvasSupported) { return; } var groupId = this.group; var mathMin = Math.min; var mathMax = Math.max; var MAX_NUMBER = Infinity; if (connectedGroups[groupId]) { var left = MAX_NUMBER; var top = MAX_NUMBER; var right = -MAX_NUMBER; var bottom = -MAX_NUMBER; var canvasList = []; var dpr = (opts && opts.pixelRatio) || 1; each$1(instances, function (chart, id) { if (chart.group === groupId) { var canvas = chart.getRenderedCanvas( clone(opts) ); var boundingRect = chart.getDom().getBoundingClientRect(); left = mathMin(boundingRect.left, left); top = mathMin(boundingRect.top, top); right = mathMax(boundingRect.right, right); bottom = mathMax(boundingRect.bottom, bottom); canvasList.push({ dom: canvas, left: boundingRect.left, top: boundingRect.top }); } }); left *= dpr; top *= dpr; right *= dpr; bottom *= dpr; var width = right - left; var height = bottom - top; var targetCanvas = createCanvas(); targetCanvas.width = width; targetCanvas.height = height; var zr = init$1(targetCanvas); each(canvasList, function (item) { var img = new ZImage({ style: { x: item.left * dpr - left, y: item.top * dpr - top, image: item.dom } }); zr.add(img); }); zr.refreshImmediately(); return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png')); } else { return this.getDataURL(opts); } }; /** * Convert from logical coordinate system to pixel coordinate system. * See CoordinateSystem#convertToPixel. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId, geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName, * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {Array|number} result */ echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel'); /** * Convert from pixel coordinate system to logical coordinate system. * See CoordinateSystem#convertFromPixel. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId / geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {Array|number} result */ echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel'); function doConvertPixel(methodName, finder, value) { var ecModel = this._model; var coordSysList = this._coordSysMgr.getCoordinateSystems(); var result; finder = parseFinder(ecModel, finder); for (var i = 0; i < coordSysList.length; i++) { var coordSys = coordSysList[i]; if (coordSys[methodName] && (result = coordSys[methodName](ecModel, finder, value)) != null ) { return result; } } if (__DEV__) { console.warn( 'No coordinate system that supports ' + methodName + ' found by the given finder.' ); } } /** * Is the specified coordinate systems or components contain the given pixel point. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId / geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName, * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {boolean} result */ echartsProto.containPixel = function (finder, value) { var ecModel = this._model; var result; finder = parseFinder(ecModel, finder); each$1(finder, function (models, key) { key.indexOf('Models') >= 0 && each$1(models, function (model) { var coordSys = model.coordinateSystem; if (coordSys && coordSys.containPoint) { result |= !!coordSys.containPoint(value); } else if (key === 'seriesModels') { var view = this._chartsMap[model.__viewId]; if (view && view.containPoint) { result |= view.containPoint(value, model); } else { if (__DEV__) { console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.' )); } } } else { if (__DEV__) { console.warn(key + ': containPoint is not supported'); } } }, this); }, this); return !!result; }; /** * Get visual from series or data. * @param {string|Object} finder * If string, e.g., 'series', means {seriesIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * dataIndex / dataIndexInside * } * If dataIndex is not specified, series visual will be fetched, * but not data item visual. * If all of seriesIndex, seriesId, seriesName are not specified, * visual will be fetched from first series. * @param {string} visualType 'color', 'symbol', 'symbolSize' */ echartsProto.getVisual = function (finder, visualType) { var ecModel = this._model; finder = parseFinder(ecModel, finder, {defaultMainType: 'series'}); var seriesModel = finder.seriesModel; if (__DEV__) { if (!seriesModel) { console.warn('There is no specified seires model'); } } var data = seriesModel.getData(); var dataIndexInside = finder.hasOwnProperty('dataIndexInside') ? finder.dataIndexInside : finder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(finder.dataIndex) : null; return dataIndexInside != null ? data.getItemVisual(dataIndexInside, visualType) : data.getVisual(visualType); }; /** * Get view of corresponding component model * @param {module:echarts/model/Component} componentModel * @return {module:echarts/view/Component} */ echartsProto.getViewOfComponentModel = function (componentModel) { return this._componentsMap[componentModel.__viewId]; }; /** * Get view of corresponding series model * @param {module:echarts/model/Series} seriesModel * @return {module:echarts/view/Chart} */ echartsProto.getViewOfSeriesModel = function (seriesModel) { return this._chartsMap[seriesModel.__viewId]; }; var updateMethods = { prepareAndUpdate: function (payload) { prepare(this); updateMethods.update.call(this, payload); }, /** * @param {Object} payload * @private */ update: function (payload) { // console.profile && console.profile('update'); var ecModel = this._model; var api = this._api; var zr = this._zr; var coordSysMgr = this._coordSysMgr; var scheduler = this._scheduler; // update before setOption if (!ecModel) { return; } ecModel.restoreData(payload); scheduler.performSeriesTasks(ecModel); // TODO // Save total ecModel here for undo/redo (after restoring data and before processing data). // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call. // Create new coordinate system each update // In LineView may save the old coordinate system and use it to get the orignal point coordSysMgr.create(ecModel, api); scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update // stream modes after data processing, where the filtered data is used to // deteming whether use progressive rendering. updateStreamModes(this, ecModel); // stackSeriesData(ecModel); coordSysMgr.update(ecModel, api); clearColorPalette(ecModel); scheduler.performVisualTasks(ecModel, payload); render(this, ecModel, api, payload); // Set background var backgroundColor = ecModel.get('backgroundColor') || 'transparent'; // In IE8 if (!env$1.canvasSupported) { var colorArr = parse(backgroundColor); backgroundColor = stringify(colorArr, 'rgb'); if (colorArr[3] === 0) { backgroundColor = 'transparent'; } } else { zr.setBackgroundColor(backgroundColor); } performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update'); }, /** * @param {Object} payload * @private */ updateTransform: function (payload) { var ecModel = this._model; var ecIns = this; var api = this._api; // update before setOption if (!ecModel) { return; } // ChartView.markUpdateMethod(payload, 'updateTransform'); var componentDirtyList = []; ecModel.eachComponent(function (componentType, componentModel) { var componentView = ecIns.getViewOfComponentModel(componentModel); if (componentView && componentView.__alive) { if (componentView.updateTransform) { var result = componentView.updateTransform(componentModel, ecModel, api, payload); result && result.update && componentDirtyList.push(componentView); } else { componentDirtyList.push(componentView); } } }); var seriesDirtyMap = createHashMap(); ecModel.eachSeries(function (seriesModel) { var chartView = ecIns._chartsMap[seriesModel.__viewId]; if (chartView.updateTransform) { var result = chartView.updateTransform(seriesModel, ecModel, api, payload); result && result.update && seriesDirtyMap.set(seriesModel.uid, 1); } else { seriesDirtyMap.set(seriesModel.uid, 1); } }); clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true); this._scheduler.performVisualTasks( ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap} ); // Currently, not call render of components. Geo render cost a lot. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList); renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap); performPostUpdateFuncs(ecModel, this._api); }, /** * @param {Object} payload * @private */ updateView: function (payload) { var ecModel = this._model; // update before setOption if (!ecModel) { return; } Chart.markUpdateMethod(payload, 'updateView'); clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true}); render(this, this._model, this._api, payload); performPostUpdateFuncs(ecModel, this._api); }, /** * @param {Object} payload * @private */ updateVisual: function (payload) { updateMethods.update.call(this, payload); // var ecModel = this._model; // // update before setOption // if (!ecModel) { // return; // } // ChartView.markUpdateMethod(payload, 'updateVisual'); // clearColorPalette(ecModel); // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true}); // render(this, this._model, this._api, payload); // performPostUpdateFuncs(ecModel, this._api); }, /** * @param {Object} payload * @private */ updateLayout: function (payload) { updateMethods.update.call(this, payload); // var ecModel = this._model; // // update before setOption // if (!ecModel) { // return; // } // ChartView.markUpdateMethod(payload, 'updateLayout'); // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true); // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true}); // render(this, this._model, this._api, payload); // performPostUpdateFuncs(ecModel, this._api); } }; function prepare(ecIns) { var ecModel = ecIns._model; var scheduler = ecIns._scheduler; scheduler.restorePipelines(ecModel); scheduler.prepareStageTasks(); prepareView(ecIns, 'component', ecModel, scheduler); prepareView(ecIns, 'chart', ecModel, scheduler); scheduler.plan(); } /** * @private */ function updateDirectly(ecIns, method, payload, mainType, subType) { var ecModel = ecIns._model; // broadcast if (!mainType) { // FIXME // Chart will not be update directly here, except set dirty. // But there is no such scenario now. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView); return; } var query = {}; query[mainType + 'Id'] = payload[mainType + 'Id']; query[mainType + 'Index'] = payload[mainType + 'Index']; query[mainType + 'Name'] = payload[mainType + 'Name']; var condition = {mainType: mainType, query: query}; subType && (condition.subType = subType); // subType may be '' by parseClassType; // If dispatchAction before setOption, do nothing. ecModel && ecModel.eachComponent(condition, function (model, index) { callView(ecIns[ mainType === 'series' ? '_chartsMap' : '_componentsMap' ][model.__viewId]); }, ecIns); function callView(view) { view && view.__alive && view[method] && view[method]( view.__model, ecModel, ecIns._api, payload ); } } /** * Resize the chart * @param {Object} opts * @param {number} [opts.width] Can be 'auto' (the same as null/undefined) * @param {number} [opts.height] Can be 'auto' (the same as null/undefined) * @param {boolean} [opts.silent=false] */ echartsProto.resize = function (opts) { if (__DEV__) { assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.'); } this._zr.resize(opts); var ecModel = this._model; // Resize loading effect this._loadingFX && this._loadingFX.resize(); if (!ecModel) { return; } var optionChanged = ecModel.resetOption('media'); var silent = opts && opts.silent; this[IN_MAIN_PROCESS] = true; optionChanged && prepare(this); updateMethods.update.call(this); this[IN_MAIN_PROCESS] = false; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); }; function updateStreamModes(ecIns, ecModel) { var chartsMap = ecIns._chartsMap; var scheduler = ecIns._scheduler; ecModel.eachSeries(function (seriesModel) { scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]); }); } /** * Show loading effect * @param {string} [name='default'] * @param {Object} [cfg] */ echartsProto.showLoading = function (name, cfg) { if (isObject(name)) { cfg = name; name = ''; } name = name || 'default'; this.hideLoading(); if (!loadingEffects[name]) { if (__DEV__) { console.warn('Loading effects ' + name + ' not exists.'); } return; } var el = loadingEffects[name](this._api, cfg); var zr = this._zr; this._loadingFX = el; zr.add(el); }; /** * Hide loading effect */ echartsProto.hideLoading = function () { this._loadingFX && this._zr.remove(this._loadingFX); this._loadingFX = null; }; /** * @param {Object} eventObj * @return {Object} */ echartsProto.makeActionFromEvent = function (eventObj) { var payload = extend({}, eventObj); payload.type = eventActionMap[eventObj.type]; return payload; }; /** * @pubilc * @param {Object} payload * @param {string} [payload.type] Action type * @param {Object|boolean} [opt] If pass boolean, means opt.silent * @param {boolean} [opt.silent=false] Whether trigger events. * @param {boolean} [opt.flush=undefined] * true: Flush immediately, and then pixel in canvas can be fetched * immediately. Caution: it might affect performance. * false: Not not flush. * undefined: Auto decide whether perform flush. */ echartsProto.dispatchAction = function (payload, opt) { if (!isObject(opt)) { opt = {silent: !!opt}; } if (!actions[payload.type]) { return; } // Avoid dispatch action before setOption. Especially in `connect`. if (!this._model) { return; } // May dispatchAction in rendering procedure if (this[IN_MAIN_PROCESS]) { this._pendingActions.push(payload); return; } doDispatchAction.call(this, payload, opt.silent); if (opt.flush) { this._zr.flush(true); } else if (opt.flush !== false && env$1.browser.weChat) { // In WeChat embeded browser, `requestAnimationFrame` and `setInterval` // hang when sliding page (on touch event), which cause that zr does not // refresh util user interaction finished, which is not expected. // But `dispatchAction` may be called too frequently when pan on touch // screen, which impacts performance if do not throttle them. this._throttledZrFlush(); } flushPendingActions.call(this, opt.silent); triggerUpdatedEvent.call(this, opt.silent); }; function doDispatchAction(payload, silent) { var payloadType = payload.type; var escapeConnect = payload.escapeConnect; var actionWrap = actions[payloadType]; var actionInfo = actionWrap.actionInfo; var cptType = (actionInfo.update || 'update').split(':'); var updateMethod = cptType.pop(); cptType = cptType[0] != null && parseClassType(cptType[0]); this[IN_MAIN_PROCESS] = true; var payloads = [payload]; var batched = false; // Batch action if (payload.batch) { batched = true; payloads = map(payload.batch, function (item) { item = defaults(extend({}, item), payload); item.batch = null; return item; }); } var eventObjBatch = []; var eventObj; var isHighDown = payloadType === 'highlight' || payloadType === 'downplay'; each(payloads, function (batchItem) { // Action can specify the event by return it. eventObj = actionWrap.action(batchItem, this._model, this._api); // Emit event outside eventObj = eventObj || extend({}, batchItem); // Convert type to eventType eventObj.type = actionInfo.event || eventObj.type; eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual. if (isHighDown) { // method, payload, mainType, subType updateDirectly(this, updateMethod, batchItem, 'series'); } else if (cptType) { updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub); } }, this); if (updateMethod !== 'none' && !isHighDown && !cptType) { // Still dirty if (this[OPTION_UPDATED]) { // FIXME Pass payload ? prepare(this); updateMethods.update.call(this, payload); this[OPTION_UPDATED] = false; } else { updateMethods[updateMethod].call(this, payload); } } // Follow the rule of action batch if (batched) { eventObj = { type: actionInfo.event || payloadType, escapeConnect: escapeConnect, batch: eventObjBatch }; } else { eventObj = eventObjBatch[0]; } this[IN_MAIN_PROCESS] = false; !silent && this._messageCenter.trigger(eventObj.type, eventObj); } function flushPendingActions(silent) { var pendingActions = this._pendingActions; while (pendingActions.length) { var payload = pendingActions.shift(); doDispatchAction.call(this, payload, silent); } } function triggerUpdatedEvent(silent) { !silent && this.trigger('updated'); } /** * Event `rendered` is triggered when zr * rendered. It is useful for realtime * snapshot (reflect animation). * * Event `finished` is triggered when: * (1) zrender rendering finished. * (2) initial animation finished. * (3) progressive rendering finished. * (4) no pending action. * (5) no delayed setOption needs to be processed. */ function bindRenderedEvent(zr, ecIns) { zr.on('rendered', function () { ecIns.trigger('rendered'); // The `finished` event should not be triggered repeatly, // so it should only be triggered when rendering indeed happend // in zrender. (Consider the case that dipatchAction is keep // triggering when mouse move). if ( // Although zr is dirty if initial animation is not finished // and this checking is called on frame, we also check // animation finished for robustness. zr.animation.isFinished() && !ecIns[OPTION_UPDATED] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length ) { ecIns.trigger('finished'); } }); } /** * @param {Object} params * @param {number} params.seriesIndex * @param {Array|TypedArray} params.data */ echartsProto.appendData = function (params) { var seriesIndex = params.seriesIndex; var ecModel = this.getModel(); var seriesModel = ecModel.getSeriesByIndex(seriesIndex); if (__DEV__) { assert(params.data && seriesModel); } seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate // system, util some scenario require that. In the expected usage of // `appendData`, the initial extent of coordinate system should better // be fixed by axis `min`/`max` setting or initial data, otherwise if // the extent changed while `appendData`, the location of the painted // graphic elements have to be changed, which make the usage of // `appendData` meaningless. this._scheduler.unfinished = true; }; /** * Register event * @method */ echartsProto.on = createRegisterEventWithLowercaseName('on'); echartsProto.off = createRegisterEventWithLowercaseName('off'); echartsProto.one = createRegisterEventWithLowercaseName('one'); /** * Prepare view instances of charts and components * @param {module:echarts/model/Global} ecModel * @private */ function prepareView(ecIns, type, ecModel, scheduler) { var isComponent = type === 'component'; var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews; var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap; var zr = ecIns._zr; var api = ecIns._api; for (var i = 0; i < viewList.length; i++) { viewList[i].__alive = false; } isComponent ? ecModel.eachComponent(function (componentType, model) { componentType !== 'series' && doPrepare(model); }) : ecModel.eachSeries(doPrepare); function doPrepare(model) { // Consider: id same and type changed. var viewId = '_ec_' + model.id + '_' + model.type; var view = viewMap[viewId]; if (!view) { var classType = parseClassType(model.type); var Clazz = isComponent ? Component.getClass(classType.main, classType.sub) : Chart.getClass(classType.sub); if (__DEV__) { assert(Clazz, classType.sub + ' does not exist.'); } view = new Clazz(); view.init(ecModel, api); viewMap[viewId] = view; viewList.push(view); zr.add(view.group); } model.__viewId = view.__id = viewId; view.__alive = true; view.__model = model; view.group.__ecComponentInfo = { mainType: model.mainType, index: model.componentIndex }; !isComponent && scheduler.prepareView(view, model, ecModel, api); } for (var i = 0; i < viewList.length;) { var view = viewList[i]; if (!view.__alive) { !isComponent && view.renderTask.dispose(); zr.remove(view.group); view.dispose(ecModel, api); viewList.splice(i, 1); delete viewMap[view.__id]; view.__id = view.group.__ecComponentInfo = null; } else { i++; } } } // /** // * Encode visual infomation from data after data processing // * // * @param {module:echarts/model/Global} ecModel // * @param {object} layout // * @param {boolean} [layoutFilter] `true`: only layout, // * `false`: only not layout, // * `null`/`undefined`: all. // * @param {string} taskBaseTag // * @private // */ // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) { // each(visualFuncs, function (visual, index) { // var isLayout = visual.isLayout; // if (layoutFilter == null // || (layoutFilter === false && !isLayout) // || (layoutFilter === true && isLayout) // ) { // visual.func(ecModel, api, payload); // } // }); // } function clearColorPalette(ecModel) { ecModel.clearColorPalette(); ecModel.eachSeries(function (seriesModel) { seriesModel.clearColorPalette(); }); } function render(ecIns, ecModel, api, payload) { renderComponents(ecIns, ecModel, api, payload); each(ecIns._chartsViews, function (chart) { chart.__alive = false; }); renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts each(ecIns._chartsViews, function (chart) { if (!chart.__alive) { chart.remove(ecModel, api); } }); } function renderComponents(ecIns, ecModel, api, payload, dirtyList) { each(dirtyList || ecIns._componentsViews, function (componentView) { var componentModel = componentView.__model; componentView.render(componentModel, ecModel, api, payload); updateZ(componentModel, componentView); }); } /** * Render each chart and component * @private */ function renderSeries(ecIns, ecModel, api, payload, dirtyMap) { // Render all charts var scheduler = ecIns._scheduler; var unfinished; ecModel.eachSeries(function (seriesModel) { var chartView = ecIns._chartsMap[seriesModel.__viewId]; chartView.__alive = true; var renderTask = chartView.renderTask; scheduler.updatePayload(renderTask, payload); if (dirtyMap && dirtyMap.get(seriesModel.uid)) { renderTask.dirty(); } unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask)); chartView.group.silent = !!seriesModel.get('silent'); updateZ(seriesModel, chartView); updateBlend(seriesModel, chartView); }); scheduler.unfinished |= unfinished; // If use hover layer updateHoverLayerStatus(ecIns._zr, ecModel); // Add aria aria(ecIns._zr.dom, ecModel); } function performPostUpdateFuncs(ecModel, api) { each(postUpdateFuncs, function (func) { func(ecModel, api); }); } var MOUSE_EVENT_NAMES = [ 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu' ]; /** * @private */ echartsProto._initEvents = function () { each(MOUSE_EVENT_NAMES, function (eveName) { this._zr.on(eveName, function (e) { var ecModel = this.getModel(); var el = e.target; var params; // no e.target when 'globalout'. if (eveName === 'globalout') { params = {}; } else if (el && el.dataIndex != null) { var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex); params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {}; } // If element has custom eventData of components else if (el && el.eventData) { params = extend({}, el.eventData); } if (params) { params.event = e; params.type = eveName; this.trigger(eveName, params); } }, this); }, this); each(eventActionMap, function (actionType, eventType) { this._messageCenter.on(eventType, function (event) { this.trigger(eventType, event); }, this); }, this); }; /** * @return {boolean} */ echartsProto.isDisposed = function () { return this._disposed; }; /** * Clear */ echartsProto.clear = function () { this.setOption({ series: [] }, true); }; /** * Dispose instance */ echartsProto.dispose = function () { if (this._disposed) { if (__DEV__) { console.warn('Instance ' + this.id + ' has been disposed'); } return; } this._disposed = true; setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, ''); var api = this._api; var ecModel = this._model; each(this._componentsViews, function (component) { component.dispose(ecModel, api); }); each(this._chartsViews, function (chart) { chart.dispose(ecModel, api); }); // Dispose after all views disposed this._zr.dispose(); delete instances[this.id]; }; mixin(ECharts, Eventful); function updateHoverLayerStatus(zr, ecModel) { var storage = zr.storage; var elCount = 0; storage.traverse(function (el) { if (!el.isGroup) { elCount++; } }); if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) { storage.traverse(function (el) { if (!el.isGroup) { // Don't switch back. el.useHoverLayer = true; } }); } } /** * Update chart progressive and blend. * @param {module:echarts/model/Series|module:echarts/model/Component} model * @param {module:echarts/view/Component|module:echarts/view/Chart} view */ function updateBlend(seriesModel, chartView) { var blendMode = seriesModel.get('blendMode') || null; if (__DEV__) { if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') { console.warn('Only canvas support blendMode'); } } chartView.group.traverse(function (el) { // FIXME marker and other components if (!el.isGroup) { // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender. if (el.style.blend !== blendMode) { el.setStyle('blend', blendMode); } } if (el.eachPendingDisplayable) { el.eachPendingDisplayable(function (displayable) { displayable.setStyle('blend', blendMode); }); } }); } /** * @param {module:echarts/model/Series|module:echarts/model/Component} model * @param {module:echarts/view/Component|module:echarts/view/Chart} view */ function updateZ(model, view) { var z = model.get('z'); var zlevel = model.get('zlevel'); // Set z and zlevel view.group.traverse(function (el) { if (el.type !== 'group') { z != null && (el.z = z); zlevel != null && (el.zlevel = zlevel); } }); } function createExtensionAPI(ecInstance) { var coordSysMgr = ecInstance._coordSysMgr; return extend(new ExtensionAPI(ecInstance), { // Inject methods getCoordinateSystems: bind( coordSysMgr.getCoordinateSystems, coordSysMgr ), getComponentByElement: function (el) { while (el) { var modelInfo = el.__ecComponentInfo; if (modelInfo != null) { return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index); } el = el.parent; } } }); } /** * @type {Object} key: actionType. * @inner */ var actions = {}; /** * Map eventType to actionType * @type {Object} */ var eventActionMap = {}; /** * Data processor functions of each stage * @type {Array.<Object.<string, Function>>} * @inner */ var dataProcessorFuncs = []; /** * @type {Array.<Function>} * @inner */ var optionPreprocessorFuncs = []; /** * @type {Array.<Function>} * @inner */ var postUpdateFuncs = []; /** * Visual encoding functions of each stage * @type {Array.<Object.<string, Function>>} */ var visualFuncs = []; /** * Theme storage * @type {Object.<key, Object>} */ var themeStorage = {}; /** * Loading effects */ var loadingEffects = {}; var instances = {}; var connectedGroups = {}; var idBase = new Date() - 0; var groupIdBase = new Date() - 0; var DOM_ATTRIBUTE_KEY = '_echarts_instance_'; var mapDataStores = {}; function enableConnect(chart) { var STATUS_PENDING = 0; var STATUS_UPDATING = 1; var STATUS_UPDATED = 2; var STATUS_KEY = '__connectUpdateStatus'; function updateConnectedChartsStatus(charts, status) { for (var i = 0; i < charts.length; i++) { var otherChart = charts[i]; otherChart[STATUS_KEY] = status; } } each(eventActionMap, function (actionType, eventType) { chart._messageCenter.on(eventType, function (event) { if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) { if (event && event.escapeConnect) { return; } var action = chart.makeActionFromEvent(event); var otherCharts = []; each(instances, function (otherChart) { if (otherChart !== chart && otherChart.group === chart.group) { otherCharts.push(otherChart); } }); updateConnectedChartsStatus(otherCharts, STATUS_PENDING); each(otherCharts, function (otherChart) { if (otherChart[STATUS_KEY] !== STATUS_UPDATING) { otherChart.dispatchAction(action); } }); updateConnectedChartsStatus(otherCharts, STATUS_UPDATED); } }); }); } /** * @param {HTMLElement} dom * @param {Object} [theme] * @param {Object} opts * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default * @param {string} [opts.renderer] Currently only 'canvas' is supported. * @param {number} [opts.width] Use clientWidth of the input `dom` by default. * Can be 'auto' (the same as null/undefined) * @param {number} [opts.height] Use clientHeight of the input `dom` by default. * Can be 'auto' (the same as null/undefined) */ function init(dom, theme$$1, opts) { if (__DEV__) { // Check version if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) { throw new Error( 'zrender/src ' + version$1 + ' is too old for ECharts ' + version + '. Current version need ZRender ' + dependencies.zrender + '+' ); } if (!dom) { throw new Error('Initialize failed: invalid dom.'); } } var existInstance = getInstanceByDom(dom); if (existInstance) { if (__DEV__) { console.warn('There is a chart instance already initialized on the dom.'); } return existInstance; } if (__DEV__) { if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && ( (!dom.clientWidth && (!opts || opts.width == null)) || (!dom.clientHeight && (!opts || opts.height == null)) ) ) { console.warn('Can\'t get dom width or height'); } } var chart = new ECharts(dom, theme$$1, opts); chart.id = 'ec_' + idBase++; instances[chart.id] = chart; setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id); enableConnect(chart); return chart; } /** * @return {string|Array.<module:echarts~ECharts>} groupId */ function connect(groupId) { // Is array of charts if (isArray(groupId)) { var charts = groupId; groupId = null; // If any chart has group each(charts, function (chart) { if (chart.group != null) { groupId = chart.group; } }); groupId = groupId || ('g_' + groupIdBase++); each(charts, function (chart) { chart.group = groupId; }); } connectedGroups[groupId] = true; return groupId; } /** * @DEPRECATED * @return {string} groupId */ function disConnect(groupId) { connectedGroups[groupId] = false; } /** * @return {string} groupId */ var disconnect = disConnect; /** * Dispose a chart instance * @param {module:echarts~ECharts|HTMLDomElement|string} chart */ function dispose(chart) { if (typeof chart === 'string') { chart = instances[chart]; } else if (!(chart instanceof ECharts)){ // Try to treat as dom chart = getInstanceByDom(chart); } if ((chart instanceof ECharts) && !chart.isDisposed()) { chart.dispose(); } } /** * @param {HTMLElement} dom * @return {echarts~ECharts} */ function getInstanceByDom(dom) { return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)]; } /** * @param {string} key * @return {echarts~ECharts} */ function getInstanceById(key) { return instances[key]; } /** * Register theme */ function registerTheme(name, theme$$1) { themeStorage[name] = theme$$1; } /** * Register option preprocessor * @param {Function} preprocessorFunc */ function registerPreprocessor(preprocessorFunc) { optionPreprocessorFuncs.push(preprocessorFunc); } /** * @param {number} [priority=1000] * @param {Object|Function} processor */ function registerProcessor(priority, processor) { normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER); } /** * Register postUpdater * @param {Function} postUpdateFunc */ function registerPostUpdate(postUpdateFunc) { postUpdateFuncs.push(postUpdateFunc); } /** * Usage: * registerAction('someAction', 'someEvent', function () { ... }); * registerAction('someAction', function () { ... }); * registerAction( * {type: 'someAction', event: 'someEvent', update: 'updateView'}, * function () { ... } * ); * * @param {(string|Object)} actionInfo * @param {string} actionInfo.type * @param {string} [actionInfo.event] * @param {string} [actionInfo.update] * @param {string} [eventName] * @param {Function} action */ function registerAction(actionInfo, eventName, action) { if (typeof eventName === 'function') { action = eventName; eventName = ''; } var actionType = isObject(actionInfo) ? actionInfo.type : ([actionInfo, actionInfo = { event: eventName }][0]); // Event name is all lowercase actionInfo.event = (actionInfo.event || actionType).toLowerCase(); eventName = actionInfo.event; // Validate action type and event name. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName)); if (!actions[actionType]) { actions[actionType] = {action: action, actionInfo: actionInfo}; } eventActionMap[eventName] = actionType; } /** * @param {string} type * @param {*} CoordinateSystem */ function registerCoordinateSystem(type, CoordinateSystem$$1) { CoordinateSystemManager.register(type, CoordinateSystem$$1); } /** * Get dimensions of specified coordinate system. * @param {string} type * @return {Array.<string|Object>} */ function getCoordinateSystemDimensions(type) { var coordSysCreator = CoordinateSystemManager.get(type); if (coordSysCreator) { return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice(); } } /** * Layout is a special stage of visual encoding * Most visual encoding like color are common for different chart * But each chart has it's own layout algorithm * * @param {number} [priority=1000] * @param {Function} layoutTask */ function registerLayout(priority, layoutTask) { normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout'); } /** * @param {number} [priority=3000] * @param {module:echarts/stream/Task} visualTask */ function registerVisual(priority, visualTask) { normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual'); } /** * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset} */ function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) { if (isFunction(priority) || isObject(priority)) { fn = priority; priority = defaultPriority; } if (__DEV__) { if (isNaN(priority) || priority == null) { throw new Error('Illegal priority'); } // Check duplicate each(targetList, function (wrap) { assert(wrap.__raw !== fn); }); } var stageHandler = Scheduler.wrapStageHandler(fn, visualType); stageHandler.__prio = priority; stageHandler.__raw = fn; targetList.push(stageHandler); return stageHandler; } /** * @param {string} name */ function registerLoading(name, loadingFx) { loadingEffects[name] = loadingFx; } /** * @param {Object} opts * @param {string} [superClass] */ function extendComponentModel(opts/*, superClass*/) { // var Clazz = ComponentModel; // if (superClass) { // var classType = parseClassType(superClass); // Clazz = ComponentModel.getClass(classType.main, classType.sub, true); // } return ComponentModel.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendComponentView(opts/*, superClass*/) { // var Clazz = ComponentView; // if (superClass) { // var classType = parseClassType(superClass); // Clazz = ComponentView.getClass(classType.main, classType.sub, true); // } return Component.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendSeriesModel(opts/*, superClass*/) { // var Clazz = SeriesModel; // if (superClass) { // superClass = 'series.' + superClass.replace('series.', ''); // var classType = parseClassType(superClass); // Clazz = ComponentModel.getClass(classType.main, classType.sub, true); // } return SeriesModel.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendChartView(opts/*, superClass*/) { // var Clazz = ChartView; // if (superClass) { // superClass = superClass.replace('series.', ''); // var classType = parseClassType(superClass); // Clazz = ChartView.getClass(classType.main, true); // } return Chart.extend(opts); } /** * ZRender need a canvas context to do measureText. * But in node environment canvas may be created by node-canvas. * So we need to specify how to create a canvas instead of using document.createElement('canvas') * * Be careful of using it in the browser. * * @param {Function} creator * @example * var Canvas = require('canvas'); * var echarts = require('echarts'); * echarts.setCanvasCreator(function () { * // Small size is enough. * return new Canvas(32, 32); * }); */ function setCanvasCreator(creator) { $override('createCanvas', creator); } /** * @param {string} mapName * @param {Object|string} geoJson * @param {Object} [specialAreas] * * @example * $.get('USA.json', function (geoJson) { * echarts.registerMap('USA', geoJson); * // Or * echarts.registerMap('USA', { * geoJson: geoJson, * specialAreas: {} * }) * }); */ function registerMap(mapName, geoJson, specialAreas) { if (geoJson.geoJson && !geoJson.features) { specialAreas = geoJson.specialAreas; geoJson = geoJson.geoJson; } if (typeof geoJson === 'string') { geoJson = (typeof JSON !== 'undefined' && JSON.parse) ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))(); } mapDataStores[mapName] = { geoJson: geoJson, specialAreas: specialAreas }; } /** * @param {string} mapName * @return {Object} */ function getMap(mapName) { return mapDataStores[mapName]; } registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor); registerPreprocessor(backwardCompat); registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack); registerLoading('default', loadingDefault); // Default actions registerAction({ type: 'highlight', event: 'highlight', update: 'highlight' }, noop); registerAction({ type: 'downplay', event: 'downplay', update: 'downplay' }, noop); // Default theme registerTheme('light', lightTheme); registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will // be mounted on `echarts` is the extension `dataTool` is imported. var dataTool = {}; var DatasetModel = extendComponentModel({ type: 'dataset', /** * @protected */ defaultOption: { // 'row', 'column' seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN, // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper" sourceHeader: null, dimensions: null, source: null }, optionUpdated: function () { detectSourceFormat(this); } }); extendComponentView({type: 'dataset'}); function defaultKeyGetter(item) { return item; } /** * @param {Array} oldArr * @param {Array} newArr * @param {Function} oldKeyGetter * @param {Function} newKeyGetter * @param {Object} [context] Can be visited by this.context in callback. */ function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) { this._old = oldArr; this._new = newArr; this._oldKeyGetter = oldKeyGetter || defaultKeyGetter; this._newKeyGetter = newKeyGetter || defaultKeyGetter; this.context = context; } DataDiffer.prototype = { constructor: DataDiffer, /** * Callback function when add a data */ add: function (func) { this._add = func; return this; }, /** * Callback function when update a data */ update: function (func) { this._update = func; return this; }, /** * Callback function when remove a data */ remove: function (func) { this._remove = func; return this; }, execute: function () { var oldArr = this._old; var newArr = this._new; var oldDataIndexMap = {}; var newDataIndexMap = {}; var oldDataKeyArr = []; var newDataKeyArr = []; var i; initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this); initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this); // Travel by inverted order to make sure order consistency // when duplicate keys exists (consider newDataIndex.pop() below). // For performance consideration, these code below do not look neat. for (i = 0; i < oldArr.length; i++) { var key = oldDataKeyArr[i]; var idx = newDataIndexMap[key]; // idx can never be empty array here. see 'set null' logic below. if (idx != null) { // Consider there is duplicate key (for example, use dataItem.name as key). // We should make sure every item in newArr and oldArr can be visited. var len = idx.length; if (len) { len === 1 && (newDataIndexMap[key] = null); idx = idx.unshift(); } else { newDataIndexMap[key] = null; } this._update && this._update(idx, i); } else { this._remove && this._remove(i); } } for (var i = 0; i < newDataKeyArr.length; i++) { var key = newDataKeyArr[i]; if (newDataIndexMap.hasOwnProperty(key)) { var idx = newDataIndexMap[key]; if (idx == null) { continue; } // idx can never be empty array here. see 'set null' logic above. if (!idx.length) { this._add && this._add(idx); } else { for (var j = 0, len = idx.length; j < len; j++) { this._add && this._add(idx[j]); } } } } } }; function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) { for (var i = 0; i < arr.length; i++) { // Add prefix to avoid conflict with Object.prototype. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i); var existence = map[key]; if (existence == null) { keyArr.push(key); map[key] = i; } else { if (!existence.length) { map[key] = existence = [existence]; } existence.push(i); } } } var OTHER_DIMENSIONS = createHashMap([ 'tooltip', 'label', 'itemName', 'itemId', 'seriesName' ]); function summarizeDimensions(data) { var summary = {}; var encode = summary.encode = {}; var notExtraCoordDimMap = createHashMap(); var defaultedLabel = []; each$1(data.dimensions, function (dimName) { var dimItem = data.getDimensionInfo(dimName); var coordDim = dimItem.coordDim; if (coordDim) { if (__DEV__) { assert$1(OTHER_DIMENSIONS.get(coordDim) == null); } var coordDimArr = encode[coordDim]; if (!encode.hasOwnProperty(coordDim)) { coordDimArr = encode[coordDim] = []; } coordDimArr[dimItem.coordDimIndex] = dimName; if (!dimItem.isExtraCoord) { notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label, // because when dataset is used, it is hard to guess which dimension // can be value dimension. If both show x, y on label is not look good, // and conventionally y axis is focused more. if (mayLabelDimType(dimItem.type)) { defaultedLabel[0] = dimName; } } } OTHER_DIMENSIONS.each(function (v, otherDim) { var otherDimArr = encode[otherDim]; if (!encode.hasOwnProperty(otherDim)) { otherDimArr = encode[otherDim] = []; } var dimIndex = dimItem.otherDims[otherDim]; if (dimIndex != null && dimIndex !== false) { otherDimArr[dimIndex] = dimItem.name; } }); }); var dataDimsOnCoord = []; var encodeFirstDimNotExtra = {}; notExtraCoordDimMap.each(function (v, coordDim) { var dimArr = encode[coordDim]; // ??? FIXME extra coord should not be set in dataDimsOnCoord. // But should fix the case that radar axes: simplify the logic // of `completeDimension`, remove `extraPrefix`. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data // dim canot on more than one coordDim. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr); }); summary.dataDimsOnCoord = dataDimsOnCoord; summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra; var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set // in this way. Use label.formatter instead. May be remove this approach someday. if (encodeLabel && encodeLabel.length) { defaultedLabel = encodeLabel.slice(); } var defaultedTooltip = defaultedLabel.slice(); var encodeTooltip = encode.tooltip; if (encodeTooltip && encodeTooltip.length) { defaultedTooltip = encodeTooltip.slice(); } encode.defaultedLabel = defaultedLabel; encode.defaultedTooltip = defaultedTooltip; return summary; } function getDimensionTypeByAxis(axisType) { return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float'; } function mayLabelDimType(dimType) { // In most cases, ordinal and time do not suitable for label. // Ordinal info can be displayed on axis. Time is too long. return !(dimType === 'ordinal' || dimType === 'time'); } // function findTheLastDimMayLabel(data) { // // Get last value dim // var dimensions = data.dimensions.slice(); // var valueType; // var valueDim; // while (dimensions.length && ( // valueDim = dimensions.pop(), // valueType = data.getDimensionInfo(valueDim).type, // valueType === 'ordinal' || valueType === 'time' // )) {} // jshint ignore:line // return valueDim; // } /** * List for data storage * @module echarts/data/List */ var isObject$4 = isObject$1; var UNDEFINED = 'undefined'; var globalObj = typeof window === UNDEFINED ? global : window; // Use prefix to avoid index to be the same as otherIdList[idx], // which will cause weird udpate animation. var ID_PREFIX = 'e\0\0'; var dataCtors = { 'float': typeof globalObj.Float64Array === UNDEFINED ? Array : globalObj.Float64Array, 'int': typeof globalObj.Int32Array === UNDEFINED ? Array : globalObj.Int32Array, // Ordinal data type can be string or int 'ordinal': Array, 'number': Array, 'time': Array }; var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array; var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array; function getIndicesCtor(list) { // The possible max value in this._indicies is always this._rawCount despite of filtering. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array; } function cloneChunk(originalChunk) { var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk); } var TRANSFERABLE_PROPERTIES = [ 'hasItemOption', '_nameList', '_idList', '_calculationInfo', '_invertedIndicesMap', '_rawData', '_rawExtent', '_chunkSize', '_chunkCount', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx' ]; function transferProperties(a, b) { each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) { if (b.hasOwnProperty(propName)) { a[propName] = b[propName]; } }); a.__wrappedMethods = b.__wrappedMethods; } /** * @constructor * @alias module:echarts/data/List * * @param {Array.<string|Object>} dimensions * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...]. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius * Spetial fields: { * ordinalMeta: <module:echarts/data/OrdinalMeta> * createInvertedIndices: <boolean> * } * @param {module:echarts/model/Model} hostModel */ var List = function (dimensions, hostModel) { dimensions = dimensions || ['x', 'y']; var dimensionInfos = {}; var dimensionNames = []; var invertedIndicesMap = {}; for (var i = 0; i < dimensions.length; i++) { // Use the original dimensions[i], where other flag props may exists. var dimensionInfo = dimensions[i]; if (isString(dimensionInfo)) { dimensionInfo = {name: dimensionInfo}; } var dimensionName = dimensionInfo.name; dimensionInfo.type = dimensionInfo.type || 'float'; if (!dimensionInfo.coordDim) { dimensionInfo.coordDim = dimensionName; dimensionInfo.coordDimIndex = 0; } dimensionInfo.otherDims = dimensionInfo.otherDims || {}; dimensionNames.push(dimensionName); dimensionInfos[dimensionName] = dimensionInfo; dimensionInfo.index = i; if (dimensionInfo.createInvertedIndices) { invertedIndicesMap[dimensionName] = []; } } /** * @readOnly * @type {Array.<string>} */ this.dimensions = dimensionNames; /** * Infomation of each data dimension, like data type. * @type {Object} */ this._dimensionInfos = dimensionInfos; /** * @type {module:echarts/model/Model} */ this.hostModel = hostModel; /** * @type {module:echarts/model/Model} */ this.dataType; /** * Indices stores the indices of data subset after filtered. * This data subset will be used in chart. * @type {Array.<number>} * @readOnly */ this._indices = null; this._count = 0; this._rawCount = 0; /** * Data storage * @type {Object.<key, Array.<TypedArray|Array>>} * @private */ this._storage = {}; /** * @type {Array.<string>} */ this._nameList = []; /** * @type {Array.<string>} */ this._idList = []; /** * Models of data option is stored sparse for optimizing memory cost * @type {Array.<module:echarts/model/Model>} * @private */ this._optionModels = []; /** * Global visual properties after visual coding * @type {Object} * @private */ this._visual = {}; /** * Globel layout properties. * @type {Object} * @private */ this._layout = {}; /** * Item visual properties after visual coding * @type {Array.<Object>} * @private */ this._itemVisuals = []; /** * Key: visual type, Value: boolean * @type {Object} * @readOnly */ this.hasItemVisual = {}; /** * Item layout properties after layout * @type {Array.<Object>} * @private */ this._itemLayouts = []; /** * Graphic elemnents * @type {Array.<module:zrender/Element>} * @private */ this._graphicEls = []; /** * Max size of each chunk. * @type {number} * @private */ this._chunkSize = 1e5; /** * @type {number} * @private */ this._chunkCount = 0; /** * @type {Array.<Array|Object>} * @private */ this._rawData; /** * Raw extent will not be cloned, but only transfered. * It will not be calculated util needed. * key: dim, * value: {end: number, extent: Array.<number>} * @type {Object} * @private */ this._rawExtent = {}; /** * @type {Object} * @private */ this._extent = {}; /** * key: dim * value: extent * @type {Object} * @private */ this._approximateExtent = {}; /** * Cache summary info for fast visit. See "dimensionHelper". * @type {Object} * @private */ this._dimensionsSummary = summarizeDimensions(this); /** * @type {Object.<Array|TypedArray>} * @private */ this._invertedIndicesMap = invertedIndicesMap; /** * @type {Object} * @private */ this._calculationInfo = {}; }; var listProto = List.prototype; listProto.type = 'list'; /** * If each data item has it's own option * @type {boolean} */ listProto.hasItemOption = true; /** * Get dimension name * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' * @return {string} Concrete dim name. */ listProto.getDimension = function (dim) { if (!isNaN(dim)) { dim = this.dimensions[dim] || dim; } return dim; }; /** * Get type and calculation info of particular dimension * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' */ listProto.getDimensionInfo = function (dim) { // Do not clone, because there may be categories in dimInfo. return this._dimensionInfos[this.getDimension(dim)]; }; /** * @return {Array.<string>} concrete dimension name list on coord. */ listProto.getDimensionsOnCoord = function () { return this._dimensionsSummary.dataDimsOnCoord.slice(); }; /** * @param {string} coordDim * @param {number} [idx] A coordDim may map to more than one data dim. * If idx is `true`, return a array of all mapped dims. * If idx is not specified, return the first dim not extra. * @return {string|Array.<string>} concrete data dim. * If idx is number, and not found, return null/undefined. * If idx is `true`, and not found, return empty array (always return array). */ listProto.mapDimension = function (coordDim, idx) { var dimensionsSummary = this._dimensionsSummary; if (idx == null) { return dimensionsSummary.encodeFirstDimNotExtra[coordDim]; } var dims = dimensionsSummary.encode[coordDim]; return idx === true // always return array if idx is `true` ? (dims || []).slice() : (dims && dims[idx]); }; /** * Initialize from data * @param {Array.<Object|number|Array>} data source or data or data provider. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and * defualt label/tooltip. * A name can be specified in encode.itemName, * or dataItem.name (only for series option data), * or provided in nameList from outside. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number */ listProto.initData = function (data, nameList, dimValueGetter) { var notProvider = Source.isInstance(data) || isArrayLike(data); if (notProvider) { data = new DefaultDataProvider(data, this.dimensions.length); } if (__DEV__) { if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) { throw new Error('Inavlid data provider.'); } } this._rawData = data; // Clear this._storage = {}; this._indices = null; this._nameList = nameList || []; this._idList = []; this._nameRepeatCount = {}; if (!dimValueGetter) { this.hasItemOption = false; } /** * @readOnly */ this.defaultDimValueGetter = defaultDimValueGetters[ this._rawData.getSource().sourceFormat ]; // Default dim value getter this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter; // Reset raw extent. this._rawExtent = {}; this._initDataFromProvider(0, data.count()); // If data has no item option. if (data.pure) { this.hasItemOption = false; } }; listProto.getProvider = function () { return this._rawData; }; listProto.appendData = function (data) { if (__DEV__) { assert$1(!this._indices, 'appendData can only be called on raw data.'); } var rawData = this._rawData; var start = this.count(); rawData.appendData(data); var end = rawData.count(); if (!rawData.persistent) { end += start; } this._initDataFromProvider(start, end); }; listProto._initDataFromProvider = function (start, end) { // Optimize. if (start >= end) { return; } var chunkSize = this._chunkSize; var rawData = this._rawData; var storage = this._storage; var dimensions = this.dimensions; var dimensionInfoMap = this._dimensionInfos; var nameList = this._nameList; var idList = this._idList; var rawExtent = this._rawExtent; var nameRepeatCount = this._nameRepeatCount = {}; var nameDimIdx; var chunkCount = this._chunkCount; var lastChunkIndex = chunkCount - 1; for (var i = 0; i < dimensions.length; i++) { var dim = dimensions[i]; if (!rawExtent[dim]) { rawExtent[dim] = getInitialExtent(); } var dimInfo = dimensionInfoMap[dim]; if (dimInfo.otherDims.itemName === 0) { nameDimIdx = this._nameDimIdx = i; } if (dimInfo.otherDims.itemId === 0) { this._idDimIdx = i; } var DataCtor = dataCtors[dimInfo.type]; if (!storage[dim]) { storage[dim] = []; } var resizeChunkArray = storage[dim][lastChunkIndex]; if (resizeChunkArray && resizeChunkArray.length < chunkSize) { var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize)); // The cost of the copy is probably inconsiderable // within the initial chunkSize. for (var j = 0; j < resizeChunkArray.length; j++) { newStore[j] = resizeChunkArray[j]; } storage[dim][lastChunkIndex] = newStore; } // Create new chunks. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) { storage[dim].push(new DataCtor(Math.min(end - k, chunkSize))); } this._chunkCount = storage[dim].length; } for (var idx = start; idx < end; idx++) { // NOTICE: Try not to write things into dataItem var dataItem = rawData.getItem(idx); // Each data item is value // [1, 2] // 2 // Bar chart, line chart which uses category axis // only gives the 'y' value. 'x' value is the indices of category // Use a tempValue to normalize the value to be a (x, y) value var chunkIndex = Math.floor(idx / chunkSize); var chunkOffset = idx % chunkSize; // Store the data by dimensions for (var k = 0; k < dimensions.length; k++) { var dim = dimensions[k]; var dimStorage = storage[dim][chunkIndex]; // PENDING NULL is empty or zero var val = this._dimValueGetter(dataItem, dim, idx, k); dimStorage[chunkOffset] = val; if (val < rawExtent[dim][0]) { rawExtent[dim][0] = val; } if (val > rawExtent[dim][1]) { rawExtent[dim][1] = val; } } // ??? FIXME not check by pure but sourceFormat? // TODO refactor these logic. if (!rawData.pure) { var name = nameList[idx]; if (dataItem && !name) { if (nameDimIdx != null) { name = this._getNameFromStore(idx); } else if (dataItem.name != null) { // There is no other place to persistent dataItem.name, // so save it to nameList. nameList[idx] = name = dataItem.name; } } // Try using the id in option // id or name is used on dynamical data, mapping old and new items. var id = dataItem == null ? null : dataItem.id; if (id == null && name != null) { // Use name as id and add counter to avoid same name nameRepeatCount[name] = nameRepeatCount[name] || 0; id = name; if (nameRepeatCount[name] > 0) { id += '__ec__' + nameRepeatCount[name]; } nameRepeatCount[name]++; } id != null && (idList[idx] = id); } } if (!rawData.persistent && rawData.clean) { // Clean unused data if data source is typed array. rawData.clean(); } this._rawCount = this._count = end; // Reset data extent this._extent = {}; prepareInvertedIndex(this); }; function prepareInvertedIndex(list) { var invertedIndicesMap = list._invertedIndicesMap; each$1(invertedIndicesMap, function (invertedIndices, dim) { var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices. var ordinalMeta = dimInfo.ordinalMeta; if (ordinalMeta) { invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array( ordinalMeta.categories.length ); // The default value of TypedArray is 0. To avoid miss // mapping to 0, we should set it as NaN. for (var i = 0; i < invertedIndices.length; i++) { invertedIndices[i] = NaN; } for (var i = 0; i < list._count; i++) { // Only support the case that all values are distinct. invertedIndices[list.get(dim, i)] = i; } } }); } // TODO refactor listProto._getNameFromStore = function (rawIndex) { var nameDimIdx = this._nameDimIdx; if (nameDimIdx != null) { var chunkSize = this._chunkSize; var chunkIndex = Math.floor(rawIndex / chunkSize); var chunkOffset = rawIndex % chunkSize; var dim = this.dimensions[nameDimIdx]; var ordinalMeta = this._dimensionInfos[dim].ordinalMeta; if (ordinalMeta) { return ordinalMeta.categories[rawIndex]; } else { var chunk = this._storage[dim][chunkIndex]; return chunk && chunk[chunkOffset]; } } }; // TODO refactor listProto._getIdFromStore = function (rawIndex) { var idDimIdx = this._idDimIdx; if (idDimIdx != null) { var chunkSize = this._chunkSize; var chunkIndex = Math.floor(rawIndex / chunkSize); var chunkOffset = rawIndex % chunkSize; var dim = this.dimensions[idDimIdx]; var ordinalMeta = this._dimensionInfos[dim].ordinalMeta; if (ordinalMeta) { return ordinalMeta.categories[rawIndex]; } else { var chunk = this._storage[dim][chunkIndex]; return chunk && chunk[chunkOffset]; } } }; /** * @return {number} */ listProto.count = function () { return this._count; }; listProto.getIndices = function () { if (this._indices) { var Ctor = this._indices.constructor; return new Ctor(this._indices.buffer, 0, this._count); } var Ctor = getIndicesCtor(this); var arr = new Ctor(this.count()); for (var i = 0; i < arr.length; i++) { arr[i] = i; } return arr; }; /** * Get value. Return NaN if idx is out of range. * @param {string} dim Dim must be concrete name. * @param {number} idx * @param {boolean} stack * @return {number} */ listProto.get = function (dim, idx /*, stack */) { if (!(idx >= 0 && idx < this._count)) { return NaN; } var storage = this._storage; if (!storage[dim]) { // TODO Warn ? return NaN; } idx = this.getRawIndex(idx); var chunkIndex = Math.floor(idx / this._chunkSize); var chunkOffset = idx % this._chunkSize; var chunkStore = storage[dim][chunkIndex]; var value = chunkStore[chunkOffset]; // FIXME ordinal data type is not stackable // if (stack) { // var dimensionInfo = this._dimensionInfos[dim]; // if (dimensionInfo && dimensionInfo.stackable) { // var stackedOn = this.stackedOn; // while (stackedOn) { // // Get no stacked data of stacked on // var stackedValue = stackedOn.get(dim, idx); // // Considering positive stack, negative stack and empty data // if ((value >= 0 && stackedValue > 0) // Positive stack // || (value <= 0 && stackedValue < 0) // Negative stack // ) { // value += stackedValue; // } // stackedOn = stackedOn.stackedOn; // } // } // } return value; }; /** * @param {string} dim concrete dim * @param {number} rawIndex * @return {number|string} */ listProto.getByRawIndex = function (dim, rawIdx) { if (!(rawIdx >= 0 && rawIdx < this._rawCount)) { return NaN; } var dimStore = this._storage[dim]; if (!dimStore) { // TODO Warn ? return NaN; } var chunkIndex = Math.floor(rawIdx / this._chunkSize); var chunkOffset = rawIdx % this._chunkSize; var chunkStore = dimStore[chunkIndex]; return chunkStore[chunkOffset]; }; /** * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange). * Hack a much simpler _getFast * @private */ listProto._getFast = function (dim, rawIdx) { var chunkIndex = Math.floor(rawIdx / this._chunkSize); var chunkOffset = rawIdx % this._chunkSize; var chunkStore = this._storage[dim][chunkIndex]; return chunkStore[chunkOffset]; }; /** * Get value for multi dimensions. * @param {Array.<string>} [dimensions] If ignored, using all dimensions. * @param {number} idx * @return {number} */ listProto.getValues = function (dimensions, idx /*, stack */) { var values = []; if (!isArray(dimensions)) { // stack = idx; idx = dimensions; dimensions = this.dimensions; } for (var i = 0, len = dimensions.length; i < len; i++) { values.push(this.get(dimensions[i], idx /*, stack */)); } return values; }; /** * If value is NaN. Inlcuding '-' * Only check the coord dimensions. * @param {string} dim * @param {number} idx * @return {number} */ listProto.hasValue = function (idx) { var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord; var dimensionInfos = this._dimensionInfos; for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) { if ( // Ordinal type can be string or number dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal' // FIXME check ordinal when using index? && isNaN(this.get(dataDimsOnCoord[i], idx)) ) { return false; } } return true; }; /** * Get extent of data in one dimension * @param {string} dim * @param {boolean} stack */ listProto.getDataExtent = function (dim /*, stack */) { // Make sure use concrete dim as cache name. dim = this.getDimension(dim); var dimData = this._storage[dim]; var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim)); if (!dimData) { return initialExtent; } // Make more strict checkings to ensure hitting cache. var currEnd = this.count(); // var cacheName = [dim, !!stack].join('_'); // var cacheName = dim; // Consider the most cases when using data zoom, `getDataExtent` // happened before filtering. We cache raw extent, which is not // necessary to be cleared and recalculated when restore data. var useRaw = !this._indices; // && !stack; var dimExtent; if (useRaw) { return this._rawExtent[dim].slice(); } dimExtent = this._extent[dim]; if (dimExtent) { return dimExtent.slice(); } dimExtent = initialExtent; var min = dimExtent[0]; var max = dimExtent[1]; for (var i = 0; i < currEnd; i++) { // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i)); var value = this._getFast(dim, this.getRawIndex(i)); value < min && (min = value); value > max && (max = value); } dimExtent = [min, max]; this._extent[dim] = dimExtent; return dimExtent; }; /** * Optimize for the scenario that data is filtered by a given extent. * Consider that if data amount is more than hundreds of thousand, * extent calculation will cost more than 10ms and the cache will * be erased because of the filtering. */ listProto.getApproximateExtent = function (dim /*, stack */) { dim = this.getDimension(dim); return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */); }; listProto.setApproximateExtent = function (extent, dim /*, stack */) { dim = this.getDimension(dim); this._approximateExtent[dim] = extent.slice(); }; /** * @param {string} key * @return {*} */ listProto.getCalculationInfo = function (key) { return this._calculationInfo[key]; }; /** * @param {string|Object} key or k-v object * @param {*} [value] */ listProto.setCalculationInfo = function (key, value) { isObject$4(key) ? extend(this._calculationInfo, key) : (this._calculationInfo[key] = value); }; /** * Get sum of data in one dimension * @param {string} dim */ listProto.getSum = function (dim /*, stack */) { var dimData = this._storage[dim]; var sum = 0; if (dimData) { for (var i = 0, len = this.count(); i < len; i++) { var value = this.get(dim, i /*, stack */); if (!isNaN(value)) { sum += value; } } } return sum; }; // /** // * Retreive the index with given value // * @param {string} dim Concrete dimension. // * @param {number} value // * @return {number} // */ // Currently incorrect: should return dataIndex but not rawIndex. // Do not fix it until this method is to be used somewhere. // FIXME Precision of float value // listProto.indexOf = function (dim, value) { // var storage = this._storage; // var dimData = storage[dim]; // var chunkSize = this._chunkSize; // if (dimData) { // for (var i = 0, len = this.count(); i < len; i++) { // var chunkIndex = Math.floor(i / chunkSize); // var chunkOffset = i % chunkSize; // if (dimData[chunkIndex][chunkOffset] === value) { // return i; // } // } // } // return -1; // }; /** * Only support the dimension which inverted index created. * Do not support other cases until required. * @param {string} concrete dim * @param {number|string} value * @return {number} rawIndex */ listProto.rawIndexOf = function (dim, value) { var invertedIndices = dim && this._invertedIndicesMap[dim]; if (__DEV__) { if (!invertedIndices) { throw new Error('Do not supported yet'); } } var rawIndex = invertedIndices[value]; if (rawIndex == null || isNaN(rawIndex)) { return -1; } return rawIndex; }; /** * Retreive the index with given name * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfName = function (name) { for (var i = 0, len = this.count(); i < len; i++) { if (this.getName(i) === name) { return i; } } return -1; }; /** * Retreive the index with given raw data index * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfRawIndex = function (rawIndex) { if (!this._indices) { return rawIndex; } if (rawIndex >= this._rawCount || rawIndex < 0) { return -1; } // Indices are ascending var indices = this._indices; // If rawIndex === dataIndex var rawDataIndex = indices[rawIndex]; if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) { return rawIndex; } var left = 0; var right = this._count - 1; while (left <= right) { var mid = (left + right) / 2 | 0; if (indices[mid] < rawIndex) { left = mid + 1; } else if (indices[mid] > rawIndex) { right = mid - 1; } else { return mid; } } return -1; }; /** * Retreive the index of nearest value * @param {string} dim * @param {number} value * @param {number} [maxDistance=Infinity] * @return {Array.<number>} Considere multiple points has the same value. */ listProto.indicesOfNearest = function (dim, value, maxDistance) { var storage = this._storage; var dimData = storage[dim]; var nearestIndices = []; if (!dimData) { return nearestIndices; } if (maxDistance == null) { maxDistance = Infinity; } var minDist = Number.MAX_VALUE; var minDiff = -1; for (var i = 0, len = this.count(); i < len; i++) { var diff = value - this.get(dim, i /*, stack */); var dist = Math.abs(diff); if (diff <= maxDistance && dist <= minDist) { // For the case of two data are same on xAxis, which has sequence data. // Show the nearest index // https://github.com/ecomfe/echarts/issues/2869 if (dist < minDist || (diff >= 0 && minDiff < 0)) { minDist = dist; minDiff = diff; nearestIndices.length = 0; } nearestIndices.push(i); } } return nearestIndices; }; /** * Get raw data index * @param {number} idx * @return {number} */ listProto.getRawIndex = getRawIndexWithoutIndices; function getRawIndexWithoutIndices(idx) { return idx; } function getRawIndexWithIndices(idx) { if (idx < this._count && idx >= 0) { return this._indices[idx]; } return -1; } /** * Get raw data item * @param {number} idx * @return {number} */ listProto.getRawDataItem = function (idx) { if (!this._rawData.persistent) { var val = []; for (var i = 0; i < this.dimensions.length; i++) { var dim = this.dimensions[i]; val.push(this.get(dim, idx)); } return val; } else { return this._rawData.getItem(this.getRawIndex(idx)); } }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getName = function (idx) { var rawIndex = this.getRawIndex(idx); return this._nameList[rawIndex] || this._getNameFromStore(rawIndex) || ''; }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getId = function (idx) { return getId(this, this.getRawIndex(idx)); }; function getId(list, rawIndex) { var id = list._idList[rawIndex]; if (id == null) { id = list._getIdFromStore(rawIndex); } if (id == null) { // FIXME Check the usage in graph, should not use prefix. id = ID_PREFIX + rawIndex; } return id; } function normalizeDimensions(dimensions) { if (!isArray(dimensions)) { dimensions = [dimensions]; } return dimensions; } function validateDimensions(list, dims) { for (var i = 0; i < dims.length; i++) { // stroage may be empty when no data, so use // dimensionInfos to check. if (!list._dimensionInfos[dims[i]]) { console.error('Unkown dimension ' + dims[i]); } } } /** * Data iteration * @param {string|Array.<string>} * @param {Function} cb * @param {*} [context=this] * * @example * list.each('x', function (x, idx) {}); * list.each(['x', 'y'], function (x, y, idx) {}); * list.each(function (idx) {}) */ listProto.each = function (dims, cb, context, contextCompat) { 'use strict'; if (!this._count) { return; } if (typeof dims === 'function') { contextCompat = context; context = cb; cb = dims; dims = []; } // contextCompat just for compat echarts3 context = context || contextCompat || this; dims = map(normalizeDimensions(dims), this.getDimension, this); if (__DEV__) { validateDimensions(this, dims); } var dimSize = dims.length; for (var i = 0; i < this.count(); i++) { // Simple optimization switch (dimSize) { case 0: cb.call(context, i); break; case 1: cb.call(context, this.get(dims[0], i), i); break; case 2: cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i); break; default: var k = 0; var value = []; for (; k < dimSize; k++) { value[k] = this.get(dims[k], i); } // Index value[k] = i; cb.apply(context, value); } } }; /** * Data filter * @param {string|Array.<string>} * @param {Function} cb * @param {*} [context=this] */ listProto.filterSelf = function (dimensions, cb, context, contextCompat) { 'use strict'; if (!this._count) { return; } if (typeof dimensions === 'function') { contextCompat = context; context = cb; cb = dimensions; dimensions = []; } // contextCompat just for compat echarts3 context = context || contextCompat || this; dimensions = map( normalizeDimensions(dimensions), this.getDimension, this ); if (__DEV__) { validateDimensions(this, dimensions); } var count = this.count(); var Ctor = getIndicesCtor(this); var newIndices = new Ctor(count); var value = []; var dimSize = dimensions.length; var offset = 0; var dim0 = dimensions[0]; for (var i = 0; i < count; i++) { var keep; var rawIdx = this.getRawIndex(i); // Simple optimization if (dimSize === 0) { keep = cb.call(context, i); } else if (dimSize === 1) { var val = this._getFast(dim0, rawIdx); keep = cb.call(context, val, i); } else { for (var k = 0; k < dimSize; k++) { value[k] = this._getFast(dim0, rawIdx); } value[k] = i; keep = cb.apply(context, value); } if (keep) { newIndices[offset++] = rawIdx; } } // Set indices after filtered. if (offset < count) { this._indices = newIndices; } this._count = offset; // Reset data extent this._extent = {}; this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices; return this; }; /** * Select data in range. (For optimization of filter) * (Manually inline code, support 5 million data filtering in data zoom.) */ listProto.selectRange = function (range /*, stack */) { 'use strict'; if (!this._count) { return; } // stack = stack || false; var dimensions = []; for (var dim in range) { if (range.hasOwnProperty(dim)) { dimensions.push(dim); } } if (__DEV__) { validateDimensions(this, dimensions); } var dimSize = dimensions.length; if (!dimSize) { return; } var originalCount = this.count(); var Ctor = getIndicesCtor(this); var newIndices = new Ctor(originalCount); var offset = 0; var dim0 = dimensions[0]; var min = range[dim0][0]; var max = range[dim0][1]; var quickFinished = false; if (!this._indices /* && !stack */) { // Extreme optimization for common case. About 2x faster in chrome. var idx = 0; if (dimSize === 1) { var dimStorage = this._storage[dimensions[0]]; for (var k = 0; k < this._chunkCount; k++) { var chunkStorage = dimStorage[k]; var len = Math.min(this._count - k * this._chunkSize, this._chunkSize); for (var i = 0; i < len; i++) { var val = chunkStorage[i]; if (val >= min && val <= max) { newIndices[offset++] = idx; } idx++; } } quickFinished = true; } else if (dimSize === 2) { var dimStorage = this._storage[dim0]; var dimStorage2 = this._storage[dimensions[1]]; var min2 = range[dimensions[1]][0]; var max2 = range[dimensions[1]][1]; for (var k = 0; k < this._chunkCount; k++) { var chunkStorage = dimStorage[k]; var chunkStorage2= dimStorage2[k]; var len = Math.min(this._count - k * this._chunkSize, this._chunkSize); for (var i = 0; i < len; i++) { var val = chunkStorage[i]; var val2 = chunkStorage2[i]; if (val >= min && val <= max && val2 >= min2 && val2 <= max2) { newIndices[offset++] = idx; } idx++; } } quickFinished = true; } } if (!quickFinished) { if (dimSize === 1) { // stack = stack || !!this.getCalculationInfo(dim0); for (var i = 0; i < originalCount; i++) { var rawIndex = this.getRawIndex(i); // var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex); var val = this._getFast(dim0, rawIndex); if (val >= min && val <= max) { newIndices[offset++] = rawIndex; } } } else { for (var i = 0; i < originalCount; i++) { var keep = true; var rawIndex = this.getRawIndex(i); for (var k = 0; k < dimSize; k++) { var dimk = dimensions[k]; // var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex); var val = this._getFast(dim, rawIndex); if (val < range[dimk][0] || val > range[dimk][1]) { keep = false; } } if (keep) { newIndices[offset++] = this.getRawIndex(i); } } } } // Set indices after filtered. if (offset < originalCount) { this._indices = newIndices; } this._count = offset; // Reset data extent this._extent = {}; this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices; return this; }; /** * Data mapping to a plain array * @param {string|Array.<string>} [dimensions] * @param {Function} cb * @param {*} [context=this] * @return {Array} */ listProto.mapArray = function (dimensions, cb, context, contextCompat) { 'use strict'; if (typeof dimensions === 'function') { contextCompat = context; context = cb; cb = dimensions; dimensions = []; } // contextCompat just for compat echarts3 context = context || contextCompat || this; var result = []; this.each(dimensions, function () { result.push(cb && cb.apply(this, arguments)); }, context); return result; }; // Data in excludeDimensions is copied, otherwise transfered. function cloneListForMapAndSample(original, excludeDimensions) { var allDimensions = original.dimensions; var list = new List( map(allDimensions, original.getDimensionInfo, original), original.hostModel ); // FIXME If needs stackedOn, value may already been stacked transferProperties(list, original); var storage = list._storage = {}; var originalStorage = original._storage; var rawExtent = extend({}, original._rawExtent); // Init storage for (var i = 0; i < allDimensions.length; i++) { var dim = allDimensions[i]; if (originalStorage[dim]) { if (indexOf(excludeDimensions, dim) >= 0) { storage[dim] = cloneDimStore(originalStorage[dim]); rawExtent[dim] = getInitialExtent(); } else { // Direct reference for other dimensions storage[dim] = originalStorage[dim]; } } } return list; } function cloneDimStore(originalDimStore) { var newDimStore = new Array(originalDimStore.length); for (var j = 0; j < originalDimStore.length; j++) { newDimStore[j] = cloneChunk(originalDimStore[j]); } return newDimStore; } function getInitialExtent() { return [Infinity, -Infinity]; } /** * Data mapping to a new List with given dimensions * @param {string|Array.<string>} dimensions * @param {Function} cb * @param {*} [context=this] * @return {Array} */ listProto.map = function (dimensions, cb, context, contextCompat) { 'use strict'; // contextCompat just for compat echarts3 context = context || contextCompat || this; dimensions = map( normalizeDimensions(dimensions), this.getDimension, this ); if (__DEV__) { validateDimensions(this, dimensions); } var list = cloneListForMapAndSample(this, dimensions); // Following properties are all immutable. // So we can reference to the same value list._indices = this._indices; list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices; var storage = list._storage; var tmpRetValue = []; var chunkSize = this._chunkSize; var dimSize = dimensions.length; var dataCount = this.count(); var values = []; var rawExtent = list._rawExtent; for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) { for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) { values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */); } values[dimSize] = dataIndex; var retValue = cb && cb.apply(context, values); if (retValue != null) { // a number or string (in oridinal dimension)? if (typeof retValue !== 'object') { tmpRetValue[0] = retValue; retValue = tmpRetValue; } var rawIndex = this.getRawIndex(dataIndex); var chunkIndex = Math.floor(rawIndex / chunkSize); var chunkOffset = rawIndex % chunkSize; for (var i = 0; i < retValue.length; i++) { var dim = dimensions[i]; var val = retValue[i]; var rawExtentOnDim = rawExtent[dim]; var dimStore = storage[dim]; if (dimStore) { dimStore[chunkIndex][chunkOffset] = val; } if (val < rawExtentOnDim[0]) { rawExtentOnDim[0] = val; } if (val > rawExtentOnDim[1]) { rawExtentOnDim[1] = val; } } } } return list; }; /** * Large data down sampling on given dimension * @param {string} dimension * @param {number} rate * @param {Function} sampleValue * @param {Function} sampleIndex Sample index for name and id */ listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) { var list = cloneListForMapAndSample(this, [dimension]); var targetStorage = list._storage; var frameValues = []; var frameSize = Math.floor(1 / rate); var dimStore = targetStorage[dimension]; var len = this.count(); var chunkSize = this._chunkSize; var rawExtentOnDim = list._rawExtent[dimension]; var newIndices = new (getIndicesCtor(this))(len); var offset = 0; for (var i = 0; i < len; i += frameSize) { // Last frame if (frameSize > len - i) { frameSize = len - i; frameValues.length = frameSize; } for (var k = 0; k < frameSize; k++) { var dataIdx = this.getRawIndex(i + k); var originalChunkIndex = Math.floor(dataIdx / chunkSize); var originalChunkOffset = dataIdx % chunkSize; frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset]; } var value = sampleValue(frameValues); var sampleFrameIdx = this.getRawIndex( Math.min(i + sampleIndex(frameValues, value) || 0, len - 1) ); var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize); var sampleChunkOffset = sampleFrameIdx % chunkSize; // Only write value on the filtered data dimStore[sampleChunkIndex][sampleChunkOffset] = value; if (value < rawExtentOnDim[0]) { rawExtentOnDim[0] = value; } if (value > rawExtentOnDim[1]) { rawExtentOnDim[1] = value; } newIndices[offset++] = sampleFrameIdx; } list._count = offset; list._indices = newIndices; list.getRawIndex = getRawIndexWithIndices; return list; }; /** * Get model of one data item. * * @param {number} idx */ // FIXME Model proxy ? listProto.getItemModel = function (idx) { var hostModel = this.hostModel; return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel); }; /** * Create a data differ * @param {module:echarts/data/List} otherList * @return {module:echarts/data/DataDiffer} */ listProto.diff = function (otherList) { var thisList = this; return new DataDiffer( otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) { return getId(otherList, idx); }, function (idx) { return getId(thisList, idx); } ); }; /** * Get visual property. * @param {string} key */ listProto.getVisual = function (key) { var visual = this._visual; return visual && visual[key]; }; /** * Set visual property * @param {string|Object} key * @param {*} [value] * * @example * setVisual('color', color); * setVisual({ * 'color': color * }); */ listProto.setVisual = function (key, val) { if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setVisual(name, key[name]); } } return; } this._visual = this._visual || {}; this._visual[key] = val; }; /** * Set layout property. * @param {string|Object} key * @param {*} [val] */ listProto.setLayout = function (key, val) { if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setLayout(name, key[name]); } } return; } this._layout[key] = val; }; /** * Get layout property. * @param {string} key. * @return {*} */ listProto.getLayout = function (key) { return this._layout[key]; }; /** * Get layout of single data item * @param {number} idx */ listProto.getItemLayout = function (idx) { return this._itemLayouts[idx]; }; /** * Set layout of single data item * @param {number} idx * @param {Object} layout * @param {boolean=} [merge=false] */ listProto.setItemLayout = function (idx, layout, merge$$1) { this._itemLayouts[idx] = merge$$1 ? extend(this._itemLayouts[idx] || {}, layout) : layout; }; /** * Clear all layout of single data item */ listProto.clearItemLayouts = function () { this._itemLayouts.length = 0; }; /** * Get visual property of single data item * @param {number} idx * @param {string} key * @param {boolean} [ignoreParent=false] */ listProto.getItemVisual = function (idx, key, ignoreParent) { var itemVisual = this._itemVisuals[idx]; var val = itemVisual && itemVisual[key]; if (val == null && !ignoreParent) { // Use global visual property return this.getVisual(key); } return val; }; /** * Set visual property of single data item * * @param {number} idx * @param {string|Object} key * @param {*} [value] * * @example * setItemVisual(0, 'color', color); * setItemVisual(0, { * 'color': color * }); */ listProto.setItemVisual = function (idx, key, value) { var itemVisual = this._itemVisuals[idx] || {}; var hasItemVisual = this.hasItemVisual; this._itemVisuals[idx] = itemVisual; if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { itemVisual[name] = key[name]; hasItemVisual[name] = true; } } return; } itemVisual[key] = value; hasItemVisual[key] = true; }; /** * Clear itemVisuals and list visual. */ listProto.clearAllVisual = function () { this._visual = {}; this._itemVisuals = []; this.hasItemVisual = {}; }; var setItemDataAndSeriesIndex = function (child) { child.seriesIndex = this.seriesIndex; child.dataIndex = this.dataIndex; child.dataType = this.dataType; }; /** * Set graphic element relative to data. It can be set as null * @param {number} idx * @param {module:zrender/Element} [el] */ listProto.setItemGraphicEl = function (idx, el) { var hostModel = this.hostModel; if (el) { // Add data index and series index for indexing the data by element // Useful in tooltip el.dataIndex = idx; el.dataType = this.dataType; el.seriesIndex = hostModel && hostModel.seriesIndex; if (el.type === 'group') { el.traverse(setItemDataAndSeriesIndex, el); } } this._graphicEls[idx] = el; }; /** * @param {number} idx * @return {module:zrender/Element} */ listProto.getItemGraphicEl = function (idx) { return this._graphicEls[idx]; }; /** * @param {Function} cb * @param {*} context */ listProto.eachItemGraphicEl = function (cb, context) { each$1(this._graphicEls, function (el, idx) { if (el) { cb && cb.call(context, el, idx); } }); }; /** * Shallow clone a new list except visual and layout properties, and graph elements. * New list only change the indices. */ listProto.cloneShallow = function (list) { if (!list) { var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this); list = new List(dimensionInfoList, this.hostModel); } // FIXME list._storage = this._storage; transferProperties(list, this); // Clone will not change the data extent and indices if (this._indices) { var Ctor = this._indices.constructor; list._indices = new Ctor(this._indices); } else { list._indices = null; } list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices; list._extent = clone(this._extent); list._approximateExtent = clone(this._approximateExtent); return list; }; /** * Wrap some method to add more feature * @param {string} methodName * @param {Function} injectFunction */ listProto.wrapMethod = function (methodName, injectFunction) { var originalMethod = this[methodName]; if (typeof originalMethod !== 'function') { return; } this.__wrappedMethods = this.__wrappedMethods || []; this.__wrappedMethods.push(methodName); this[methodName] = function () { var res = originalMethod.apply(this, arguments); return injectFunction.apply(this, [res].concat(slice(arguments))); }; }; // Methods that create a new list based on this list should be listed here. // Notice that those method should `RETURN` the new list. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map']; // Methods that change indices of this list should be listed here. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange']; /** * @deprecated * Use `echarts/data/helper/createDimensions` instead. */ /** * @see {module:echarts/test/ut/spec/data/completeDimensions} * * Complete the dimensions array, by user defined `dimension` and `encode`, * and guessing from the data structure. * If no 'value' dimension specified, the first no-named dimension will be * named as 'value'. * * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which * provides not only dim template, but also default order. * properties: 'name', 'type', 'displayName'. * `name` of each item provides default coord name. * [{dimsDef: [string...]}, ...] dimsDef of sysDim item provides default dim name, and * provide dims count that the sysDim required. * [{ordinalMeta}] can be specified. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious) * @param {Object} [opt] * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions * For example: ['asdf', {name, type}, ...]. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3} * @param {string} [opt.generateCoord] Generate coord dim with the given name. * If not specified, extra dim names will be: * 'value', 'value0', 'value1', ... * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`. * If `generateCoordCount` specified, the generated dim names will be: * `generateCoord` + 0, `generateCoord` + 1, ... * can be Infinity, indicate that use all of the remain columns. * @param {number} [opt.dimCount] If not specified, guess by the first data item. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim. * @return {Array.<Object>} [{ * name: string mandatory, * displayName: string, the origin name in dimsDef, see source helper. * If displayName given, the tooltip will displayed vertically. * coordDim: string mandatory, * coordDimIndex: number mandatory, * type: string optional, * otherDims: { never null/undefined * tooltip: number optional, * label: number optional, * itemName: number optional, * seriesName: number optional, * }, * isExtraCoord: boolean true if coord is generated * (not specified in encode and not series specified) * other props ... * }] */ function completeDimensions(sysDims, source, opt) { if (!Source.isInstance(source)) { source = Source.seriesDataToSource(source); } opt = opt || {}; sysDims = (sysDims || []).slice(); var dimsDef = (opt.dimsDef || []).slice(); var encodeDef = createHashMap(opt.encodeDef); var dataDimNameMap = createHashMap(); var coordDimNameMap = createHashMap(); // var valueCandidate; var result = []; var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result. for (var i = 0; i < dimCount; i++) { var dimDefItem = dimsDef[i] = extend( {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]} ); var userDimName = dimDefItem.name; var resultItem = result[i] = {otherDims: {}}; // Name will be applied later for avoiding duplication. if (userDimName != null && dataDimNameMap.get(userDimName) == null) { // Only if `series.dimensions` is defined in option // displayName, will be set, and dimension will be diplayed vertically in // tooltip by default. resultItem.name = resultItem.displayName = userDimName; dataDimNameMap.set(userDimName, i); } dimDefItem.type != null && (resultItem.type = dimDefItem.type); dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName); } // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`. encodeDef.each(function (dataDims, coordDim) { dataDims = normalizeToArray(dataDims).slice(); var validDataDims = encodeDef.set(coordDim, []); each$1(dataDims, function (resultDimIdx, idx) { // The input resultDimIdx can be dim name or index. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx)); if (resultDimIdx != null && resultDimIdx < dimCount) { validDataDims[idx] = resultDimIdx; applyDim(result[resultDimIdx], coordDim, idx); } }); }); // Apply templetes and default order from `sysDims`. var availDimIdx = 0; each$1(sysDims, function (sysDimItem, sysDimIndex) { var coordDim; var sysDimItem; var sysDimItemDimsDef; var sysDimItemOtherDims; if (isString(sysDimItem)) { coordDim = sysDimItem; sysDimItem = {}; } else { coordDim = sysDimItem.name; var ordinalMeta = sysDimItem.ordinalMeta; sysDimItem.ordinalMeta = null; sysDimItem = clone(sysDimItem); sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly. sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemOtherDims = sysDimItem.otherDims; sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null; } var dataDims = normalizeToArray(encodeDef.get(coordDim)); // dimensions provides default dim sequences. if (!dataDims.length) { for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) { while (availDimIdx < result.length && result[availDimIdx].coordDim != null) { availDimIdx++; } availDimIdx < result.length && dataDims.push(availDimIdx++); } } // Apply templates. each$1(dataDims, function (resultDimIdx, coordDimIndex) { var resultItem = result[resultDimIdx]; applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex); if (resultItem.name == null && sysDimItemDimsDef) { resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex]; } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}} sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims); }); }); function applyDim(resultItem, coordDim, coordDimIndex) { if (OTHER_DIMENSIONS.get(coordDim) != null) { resultItem.otherDims[coordDim] = coordDimIndex; } else { resultItem.coordDim = coordDim; resultItem.coordDimIndex = coordDimIndex; coordDimNameMap.set(coordDim, true); } } // Make sure the first extra dim is 'value'. var generateCoord = opt.generateCoord; var generateCoordCount = opt.generateCoordCount; var fromZero = generateCoordCount != null; generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0; var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) { var resultItem = result[resultDimIdx] = result[resultDimIdx] || {}; var coordDim = resultItem.coordDim; if (coordDim == null) { resultItem.coordDim = genName( extra, coordDimNameMap, fromZero ); resultItem.coordDimIndex = 0; if (!generateCoord || generateCoordCount <= 0) { resultItem.isExtraCoord = true; } generateCoordCount--; } resultItem.name == null && (resultItem.name = genName( resultItem.coordDim, dataDimNameMap )); if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) { resultItem.type = 'ordinal'; } } return result; } // ??? TODO // Originally detect dimCount by data[0]. Should we // optimize it to only by sysDims and dimensions and encode. // So only necessary dims will be initialized. // But // (1) custom series should be considered. where other dims // may be visited. // (2) sometimes user need to calcualte bubble size or use visualMap // on other dimensions besides coordSys needed. // So, dims that is not used by system, should be shared in storage? function getDimCount(source, sysDims, dimsDef, optDimCount) { // Note that the result dimCount should not small than columns count // of data, otherwise `dataDimNameMap` checking will be incorrect. var dimCount = Math.max( source.dimensionsDetectCount || 1, sysDims.length, dimsDef.length, optDimCount || 0 ); each$1(sysDims, function (sysDimItem) { var sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length)); }); return dimCount; } function genName(name, map$$1, fromZero) { if (fromZero || map$$1.get(name) != null) { var i = 0; while (map$$1.get(name + i) != null) { i++; } name += i; } map$$1.set(name, true); return name; } /** * Substitute `completeDimensions`. * `completeDimensions` is to be deprecated. */ /** * @param {module:echarts/data/Source|module:echarts/data/List} source or data. * @param {Object|Array} [opt] * @param {Array.<string|Object>} [opt.coordDimensions=[]] * @param {number} [opt.dimensionsCount] * @param {string} [opt.generateCoord] * @param {string} [opt.generateCoordCount] * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define. * @return {Array.<Object>} dimensionsInfo */ var createDimensions = function (source, opt) { opt = opt || {}; return completeDimensions(opt.coordDimensions || [], source, { dimsDef: opt.dimensionsDefine || source.dimensionsDefine, encodeDef: opt.encodeDefine || source.encodeDefine, dimCount: opt.dimensionsCount, generateCoord: opt.generateCoord, generateCoordCount: opt.generateCoordCount }); }; /** * Note that it is too complicated to support 3d stack by value * (have to create two-dimension inverted index), so in 3d case * we just support that stacked by index. * * @param {module:echarts/model/Series} seriesModel * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>. * The input dimensionInfoList will be modified. * @param {Object} [opt] * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed. * @param {boolean} [opt.byIndex=false] * @return {Object} calculationInfo * { * stackedDimension: string * stackedByDimension: string * isStackedByIndex: boolean * stackedOverDimension: string * stackResultDimension: string * } */ function enableDataStack(seriesModel, dimensionInfoList, opt) { opt = opt || {}; var byIndex = opt.byIndex; var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack. var mayStack = !!(seriesModel && seriesModel.get('stack')); var stackedByDimInfo; var stackedDimInfo; var stackResultDimension; var stackedOverDimension; each$1(dimensionInfoList, function (dimensionInfo, index) { if (isString(dimensionInfo)) { dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo}; } if (mayStack && !dimensionInfo.isExtraCoord) { // Find the first ordinal dimension as the stackedByDimInfo. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) { stackedByDimInfo = dimensionInfo; } // Find the first stackable dimension as the stackedDimInfo. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim) ) { stackedDimInfo = dimensionInfo; } } }); // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`. // That put stack logic in List is for using conveniently in echarts extensions, but it // might not be a good way. if (stackedDimInfo && (byIndex || stackedByDimInfo)) { // Use a weird name that not duplicated with other names. stackResultDimension = '__\0ecstackresult'; stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value. if (stackedByDimInfo) { stackedByDimInfo.createInvertedIndices = true; } var stackedDimCoordDim = stackedDimInfo.coordDim; var stackedDimType = stackedDimInfo.type; var stackedDimCoordIndex = 0; each$1(dimensionInfoList, function (dimensionInfo) { if (dimensionInfo.coordDim === stackedDimCoordDim) { stackedDimCoordIndex++; } }); dimensionInfoList.push({ name: stackResultDimension, coordDim: stackedDimCoordDim, coordDimIndex: stackedDimCoordIndex, type: stackedDimType, isExtraCoord: true, isCalculationCoord: true }); stackedDimCoordIndex++; dimensionInfoList.push({ name: stackedOverDimension, // This dimension contains stack base (generally, 0), so do not set it as // `stackedDimCoordDim` to avoid extent calculation, consider log scale. coordDim: stackedOverDimension, coordDimIndex: stackedDimCoordIndex, type: stackedDimType, isExtraCoord: true, isCalculationCoord: true }); } return { stackedDimension: stackedDimInfo && stackedDimInfo.name, stackedByDimension: stackedByDimInfo && stackedByDimInfo.name, isStackedByIndex: byIndex, stackedOverDimension: stackedOverDimension, stackResultDimension: stackResultDimension }; } /** * @param {module:echarts/data/List} data * @param {string} stackedDim * @param {string} [stackedByDim] If not input this parameter, check whether * stacked by index. */ function isDimensionStacked(data, stackedDim, stackedByDim) { return stackedDim && stackedDim === data.getCalculationInfo('stackedDimension') && ( stackedByDim != null ? stackedByDim === data.getCalculationInfo('stackedByDimension') : data.getCalculationInfo('isStackedByIndex') ); } /** * @param {module:echarts/data/Source|Array} source Or raw data. * @param {module:echarts/model/Series} seriesModel * @param {Object} [opt] * @param {string} [opt.generateCoord] */ function createListFromArray(source, seriesModel, opt) { opt = opt || {}; if (!Source.isInstance(source)) { source = Source.seriesDataToSource(source); } var coordSysName = seriesModel.get('coordinateSystem'); var registeredCoordSys = CoordinateSystemManager.get(coordSysName); var coordSysDefine = getCoordSysDefineBySeries(seriesModel); var coordSysDimDefs; if (coordSysDefine) { coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) { var dimInfo = {name: dim}; var axisModel = coordSysDefine.axisMap.get(dim); if (axisModel) { var axisType = axisModel.get('type'); dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType); } return dimInfo; }); } if (!coordSysDimDefs) { // Get dimensions from registered coordinate system coordSysDimDefs = (registeredCoordSys && ( registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice() )) || ['x', 'y']; } var dimInfoList = createDimensions(source, { coordDimensions: coordSysDimDefs, generateCoord: opt.generateCoord }); var firstCategoryDimIndex; var hasNameEncode; coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) { var coordDim = dimInfo.coordDim; var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim); if (categoryAxisModel) { if (firstCategoryDimIndex == null) { firstCategoryDimIndex = dimIndex; } dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta(); } if (dimInfo.otherDims.itemName != null) { hasNameEncode = true; } }); if (!hasNameEncode && firstCategoryDimIndex != null) { dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0; } var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList); var list = new List(dimInfoList, seriesModel); list.setCalculationInfo(stackCalculationInfo); var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source)) ? function (itemOpt, dimName, dataIndex, dimIndex) { // Use dataIndex as ordinal value in categoryAxis return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex); } : null; list.hasItemOption = false; list.initData(source, null, dimValueGetter); return list; } function isNeedCompleteOrdinalData(source) { if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) { var sampleItem = firstDataNotNull(source.data || []); return sampleItem != null && !isArray(getDataItemValue(sampleItem)); } } function firstDataNotNull(data) { var i = 0; while (i < data.length && data[i] == null) { i++; } return data[i]; } SeriesModel.extend({ type: 'series.line', dependencies: ['grid', 'polar'], getInitialData: function (option, ecModel) { if (__DEV__) { var coordSys = option.coordinateSystem; if (coordSys !== 'polar' && coordSys !== 'cartesian2d') { throw new Error('Line not support coordinateSystem besides cartesian and polar'); } } return createListFromArray(this.getSource(), this); }, defaultOption: { zlevel: 0, // 一级层叠 z: 2, // 二级层叠 coordinateSystem: 'cartesian2d', legendHoverLink: true, hoverAnimation: true, // stack: null // xAxisIndex: 0, // yAxisIndex: 0, // polarIndex: 0, // If clip the overflow value clipOverflow: true, // cursor: null, label: { position: 'top' }, // itemStyle: { // }, lineStyle: { width: 2, type: 'solid' }, // areaStyle: { // origin of areaStyle. Valid values: // `'auto'/null/undefined`: from axisLine to data // `'start'`: from min to data // `'end'`: from data to max // origin: 'auto' // }, // false, 'start', 'end', 'middle' step: false, // Disabled if step is true smooth: false, smoothMonotone: null, // 拐点图形类型 symbol: 'emptyCircle', // 拐点图形大小 symbolSize: 4, // 拐点图形旋转控制 symbolRotate: null, // 是否显示 symbol, 只有在 tooltip hover 的时候显示 showSymbol: true, // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略) showAllSymbol: false, // 是否连接断点 connectNulls: false, // 数据过滤,'average', 'max', 'min', 'sum' sampling: 'none', animationEasing: 'linear', // Disable progressive progressive: 0, hoverLayerThreshold: Infinity } }); // Symbol factory /** * Triangle shape * @inner */ var Triangle = extendShape({ type: 'triangle', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy + height); path.lineTo(cx - width, cy + height); path.closePath(); } }); /** * Diamond shape * @inner */ var Diamond = extendShape({ type: 'diamond', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height); path.lineTo(cx - width, cy); path.closePath(); } }); /** * Pin shape * @inner */ var Pin = extendShape({ type: 'pin', shape: { // x, y on the cusp x: 0, y: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var x = shape.x; var y = shape.y; var w = shape.width / 5 * 3; // Height must be larger than width var h = Math.max(w, shape.height); var r = w / 2; // Dist on y with tangent point and circle center var dy = r * r / (h - r); var cy = y - h + r + dy; var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center var dx = Math.cos(angle) * r; var tanX = Math.sin(angle); var tanY = Math.cos(angle); var cpLen = r * 0.6; var cpLen2 = r * 0.7; path.moveTo(x - dx, cy + dy); path.arc( x, cy, r, Math.PI - angle, Math.PI * 2 + angle ); path.bezierCurveTo( x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y ); path.bezierCurveTo( x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy ); path.closePath(); } }); /** * Arrow shape * @inner */ var Arrow = extendShape({ type: 'arrow', shape: { x: 0, y: 0, width: 0, height: 0 }, buildPath: function (ctx, shape) { var height = shape.height; var width = shape.width; var x = shape.x; var y = shape.y; var dx = width / 3 * 2; ctx.moveTo(x, y); ctx.lineTo(x + dx, y + height); ctx.lineTo(x, y + height / 4 * 3); ctx.lineTo(x - dx, y + height); ctx.lineTo(x, y); ctx.closePath(); } }); /** * Map of path contructors * @type {Object.<string, module:zrender/graphic/Path>} */ var symbolCtors = { line: Line, rect: Rect, roundRect: Rect, square: Rect, circle: Circle, diamond: Diamond, pin: Pin, arrow: Arrow, triangle: Triangle }; var symbolShapeMakers = { line: function (x, y, w, h, shape) { // FIXME shape.x1 = x; shape.y1 = y + h / 2; shape.x2 = x + w; shape.y2 = y + h / 2; }, rect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; }, roundRect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; shape.r = Math.min(w, h) / 4; }, square: function (x, y, w, h, shape) { var size = Math.min(w, h); shape.x = x; shape.y = y; shape.width = size; shape.height = size; }, circle: function (x, y, w, h, shape) { // Put circle in the center of square shape.cx = x + w / 2; shape.cy = y + h / 2; shape.r = Math.min(w, h) / 2; }, diamond: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; }, pin: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, arrow: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, triangle: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; } }; var symbolBuildProxies = {}; each$1(symbolCtors, function (Ctor, name) { symbolBuildProxies[name] = new Ctor(); }); var SymbolClz$2 = extendShape({ type: 'symbol', shape: { symbolType: '', x: 0, y: 0, width: 0, height: 0 }, beforeBrush: function () { var style = this.style; var shape = this.shape; // FIXME if (shape.symbolType === 'pin' && style.textPosition === 'inside') { style.textPosition = ['50%', '40%']; style.textAlign = 'center'; style.textVerticalAlign = 'middle'; } }, buildPath: function (ctx, shape, inBundle) { var symbolType = shape.symbolType; var proxySymbol = symbolBuildProxies[symbolType]; if (shape.symbolType !== 'none') { if (!proxySymbol) { // Default rect symbolType = 'rect'; proxySymbol = symbolBuildProxies[symbolType]; } symbolShapeMakers[symbolType]( shape.x, shape.y, shape.width, shape.height, proxySymbol.shape ); proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle); } } }); // Provide setColor helper method to avoid determine if set the fill or stroke outside function symbolPathSetColor(color, innerColor) { if (this.type !== 'image') { var symbolStyle = this.style; var symbolShape = this.shape; if (symbolShape && symbolShape.symbolType === 'line') { symbolStyle.stroke = color; } else if (this.__isEmptyBrush) { symbolStyle.stroke = color; symbolStyle.fill = innerColor || '#fff'; } else { // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ? symbolStyle.fill && (symbolStyle.fill = color); symbolStyle.stroke && (symbolStyle.stroke = color); } this.dirty(false); } } /** * Create a symbol element with given symbol configuration: shape, x, y, width, height, color * @param {string} symbolType * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {string} color * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h, * for path and image only. */ function createSymbol(symbolType, x, y, w, h, color, keepAspect) { // TODO Support image object, DynamicImage. var isEmpty = symbolType.indexOf('empty') === 0; if (isEmpty) { symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6); } var symbolPath; if (symbolType.indexOf('image://') === 0) { symbolPath = makeImage( symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover' ); } else if (symbolType.indexOf('path://') === 0) { symbolPath = makePath( symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover' ); } else { symbolPath = new SymbolClz$2({ shape: { symbolType: symbolType, x: x, y: y, width: w, height: h } }); } symbolPath.__isEmptyBrush = isEmpty; symbolPath.setColor = symbolPathSetColor; symbolPath.setColor(color); return symbolPath; } /** * @param {module:echarts/data/List} data * @param {number} dataIndex * @return {string} label string. Not null/undefined */ function getDefaultLabel(data, dataIndex) { var labelDims = data.mapDimension('defaultedLabel', true); var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1) if (len === 1) { return retrieveRawValue(data, dataIndex, labelDims[0]); } else if (len) { var vals = []; for (var i = 0; i < labelDims.length; i++) { var val = retrieveRawValue(data, dataIndex, labelDims[i]); vals.push(val); } return vals.join(' '); } } /** * @module echarts/chart/helper/Symbol */ function getSymbolSize(data, idx) { var symbolSize = data.getItemVisual(idx, 'symbolSize'); return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize]; } function getScale(symbolSize) { return [symbolSize[0] / 2, symbolSize[1] / 2]; } /** * @constructor * @alias {module:echarts/chart/helper/Symbol} * @param {module:echarts/data/List} data * @param {number} idx * @extends {module:zrender/graphic/Group} */ function SymbolClz(data, idx, seriesScope) { Group.call(this); this.updateData(data, idx, seriesScope); } var symbolProto = SymbolClz.prototype; function driftSymbol(dx, dy) { this.parent.drift(dx, dy); } symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) { // Remove paths created before this.removeAll(); var color = data.getItemVisual(idx, 'color'); // var symbolPath = createSymbol( // symbolType, -0.5, -0.5, 1, 1, color // ); // If width/height are set too small (e.g., set to 1) on ios10 // and macOS Sierra, a circle stroke become a rect, no matter what // the scale is set. So we set width/height as 2. See #4150. var symbolPath = createSymbol( symbolType, -1, -1, 2, 2, color ); symbolPath.attr({ z2: 100, culling: true, scale: getScale(symbolSize) }); // Rewrite drift method symbolPath.drift = driftSymbol; this._symbolType = symbolType; this.add(symbolPath); }; /** * Stop animation * @param {boolean} toLastFrame */ symbolProto.stopSymbolAnimation = function (toLastFrame) { this.childAt(0).stopAnimation(toLastFrame); }; /** * FIXME: * Caution: This method breaks the encapsulation of this module, * but it indeed brings convenience. So do not use the method * unless you detailedly know all the implements of `Symbol`, * especially animation. * * Get symbol path element. */ symbolProto.getSymbolPath = function () { return this.childAt(0); }; /** * Get scale(aka, current symbol size). * Including the change caused by animation */ symbolProto.getScale = function () { return this.childAt(0).scale; }; /** * Highlight symbol */ symbolProto.highlight = function () { this.childAt(0).trigger('emphasis'); }; /** * Downplay symbol */ symbolProto.downplay = function () { this.childAt(0).trigger('normal'); }; /** * @param {number} zlevel * @param {number} z */ symbolProto.setZ = function (zlevel, z) { var symbolPath = this.childAt(0); symbolPath.zlevel = zlevel; symbolPath.z = z; }; symbolProto.setDraggable = function (draggable) { var symbolPath = this.childAt(0); symbolPath.draggable = draggable; symbolPath.cursor = draggable ? 'move' : 'pointer'; }; /** * Update symbol properties * @param {module:echarts/data/List} data * @param {number} idx * @param {Object} [seriesScope] * @param {Object} [seriesScope.itemStyle] * @param {Object} [seriesScope.hoverItemStyle] * @param {Object} [seriesScope.symbolRotate] * @param {Object} [seriesScope.symbolOffset] * @param {module:echarts/model/Model} [seriesScope.labelModel] * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel] * @param {boolean} [seriesScope.hoverAnimation] * @param {Object} [seriesScope.cursorStyle] * @param {module:echarts/model/Model} [seriesScope.itemModel] * @param {string} [seriesScope.symbolInnerColor] * @param {Object} [seriesScope.fadeIn=false] */ symbolProto.updateData = function (data, idx, seriesScope) { this.silent = false; var symbolType = data.getItemVisual(idx, 'symbol') || 'circle'; var seriesModel = data.hostModel; var symbolSize = getSymbolSize(data, idx); var isInit = symbolType !== this._symbolType; if (isInit) { this._createSymbol(symbolType, data, idx, symbolSize); } else { var symbolPath = this.childAt(0); symbolPath.silent = false; updateProps(symbolPath, { scale: getScale(symbolSize) }, seriesModel, idx); } this._updateCommon(data, idx, symbolSize, seriesScope); if (isInit) { var symbolPath = this.childAt(0); var fadeIn = seriesScope && seriesScope.fadeIn; var target = {scale: symbolPath.scale.slice()}; fadeIn && (target.style = {opacity: symbolPath.style.opacity}); symbolPath.scale = [0, 0]; fadeIn && (symbolPath.style.opacity = 0); initProps(symbolPath, target, seriesModel, idx); } this._seriesModel = seriesModel; }; // Update common properties var normalStyleAccessPath = ['itemStyle']; var emphasisStyleAccessPath = ['emphasis', 'itemStyle']; var normalLabelAccessPath = ['label']; var emphasisLabelAccessPath = ['emphasis', 'label']; /** * @param {module:echarts/data/List} data * @param {number} idx * @param {Array.<number>} symbolSize * @param {Object} [seriesScope] */ symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) { var symbolPath = this.childAt(0); var seriesModel = data.hostModel; var color = data.getItemVisual(idx, 'color'); // Reset style if (symbolPath.type !== 'image') { symbolPath.useStyle({ strokeNoScale: true }); } var itemStyle = seriesScope && seriesScope.itemStyle; var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle; var symbolRotate = seriesScope && seriesScope.symbolRotate; var symbolOffset = seriesScope && seriesScope.symbolOffset; var labelModel = seriesScope && seriesScope.labelModel; var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel; var hoverAnimation = seriesScope && seriesScope.hoverAnimation; var cursorStyle = seriesScope && seriesScope.cursorStyle; if (!seriesScope || data.hasItemOption) { var itemModel = (seriesScope && seriesScope.itemModel) ? seriesScope.itemModel : data.getItemModel(idx); // Color must be excluded. // Because symbol provide setColor individually to set fill and stroke itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']); hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle(); symbolRotate = itemModel.getShallow('symbolRotate'); symbolOffset = itemModel.getShallow('symbolOffset'); labelModel = itemModel.getModel(normalLabelAccessPath); hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath); hoverAnimation = itemModel.getShallow('hoverAnimation'); cursorStyle = itemModel.getShallow('cursor'); } else { hoverItemStyle = extend({}, hoverItemStyle); } var elStyle = symbolPath.style; symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0); if (symbolOffset) { symbolPath.attr('position', [ parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1]) ]); } cursorStyle && symbolPath.attr('cursor', cursorStyle); // PENDING setColor before setStyle!!! symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor); symbolPath.setStyle(itemStyle); var opacity = data.getItemVisual(idx, 'opacity'); if (opacity != null) { elStyle.opacity = opacity; } var useNameLabel = seriesScope && seriesScope.useNameLabel; setLabelStyle( elStyle, hoverItemStyle, labelModel, hoverLabelModel, { labelFetcher: seriesModel, labelDataIndex: idx, defaultText: getLabelDefaultText, isRectText: true, autoColor: color } ); // Do not execute util needed. function getLabelDefaultText(idx, opt) { return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx); } symbolPath.off('mouseover') .off('mouseout') .off('emphasis') .off('normal'); symbolPath.hoverStyle = hoverItemStyle; // FIXME // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead. setHoverStyle(symbolPath); var scale = getScale(symbolSize); if (hoverAnimation && seriesModel.isAnimationEnabled()) { var onEmphasis = function() { // Do not support this hover animation util some scenario required. // Animation can only be supported in hover layer when using `el.incremetal`. if (this.incremental) { return; } var ratio = scale[1] / scale[0]; this.animateTo({ scale: [ Math.max(scale[0] * 1.1, scale[0] + 3), Math.max(scale[1] * 1.1, scale[1] + 3 * ratio) ] }, 400, 'elasticOut'); }; var onNormal = function() { if (this.incremental) { return; } this.animateTo({ scale: scale }, 400, 'elasticOut'); }; symbolPath.on('mouseover', onEmphasis) .on('mouseout', onNormal) .on('emphasis', onEmphasis) .on('normal', onNormal); } }; /** * @param {Function} cb * @param {Object} [opt] * @param {Object} [opt.keepLabel=true] */ symbolProto.fadeOut = function (cb, opt) { var symbolPath = this.childAt(0); // Avoid mistaken hover when fading out this.silent = symbolPath.silent = true; // Not show text when animating !(opt && opt.keepLabel) && (symbolPath.style.text = null); updateProps( symbolPath, { style: {opacity: 0}, scale: [0, 0] }, this._seriesModel, this.dataIndex, cb ); }; inherits(SymbolClz, Group); /** * @module echarts/chart/helper/SymbolDraw */ /** * @constructor * @alias module:echarts/chart/helper/SymbolDraw * @param {module:zrender/graphic/Group} [symbolCtor] */ function SymbolDraw(symbolCtor) { this.group = new Group(); this._symbolCtor = symbolCtor || SymbolClz; } var symbolDrawProto = SymbolDraw.prototype; function symbolNeedsDraw(data, point, idx, opt) { return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will // cut part of the symbol element shape. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none'; } /** * Update symbols draw by new data * @param {module:echarts/data/List} data * @param {Object} [opt] Or isIgnore * @param {Function} [opt.isIgnore] * @param {Object} [opt.clipShape] */ symbolDrawProto.updateData = function (data, opt) { opt = normalizeUpdateOpt(opt); var group = this.group; var seriesModel = data.hostModel; var oldData = this._data; var SymbolCtor = this._symbolCtor; var seriesScope = makeSeriesScope(data); // There is no oldLineData only when first rendering or switching from // stream mode to normal mode, where previous elements should be removed. if (!oldData) { group.removeAll(); } data.diff(oldData) .add(function (newIdx) { var point = data.getItemLayout(newIdx); if (symbolNeedsDraw(data, point, newIdx, opt)) { var symbolEl = new SymbolCtor(data, newIdx, seriesScope); symbolEl.attr('position', point); data.setItemGraphicEl(newIdx, symbolEl); group.add(symbolEl); } }) .update(function (newIdx, oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx); var point = data.getItemLayout(newIdx); if (!symbolNeedsDraw(data, point, newIdx, opt)) { group.remove(symbolEl); return; } if (!symbolEl) { symbolEl = new SymbolCtor(data, newIdx); symbolEl.attr('position', point); } else { symbolEl.updateData(data, newIdx, seriesScope); updateProps(symbolEl, { position: point }, seriesModel); } // Add back group.add(symbolEl); data.setItemGraphicEl(newIdx, symbolEl); }) .remove(function (oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); el && el.fadeOut(function () { group.remove(el); }); }) .execute(); this._data = data; }; symbolDrawProto.isPersistent = function () { return true; }; symbolDrawProto.updateLayout = function () { var data = this._data; if (data) { // Not use animation data.eachItemGraphicEl(function (el, idx) { var point = data.getItemLayout(idx); el.attr('position', point); }); } }; symbolDrawProto.incrementalPrepareUpdate = function (data) { this._seriesScope = makeSeriesScope(data); this._data = null; this.group.removeAll(); }; /** * Update symbols draw by new data * @param {module:echarts/data/List} data * @param {Object} [opt] Or isIgnore * @param {Function} [opt.isIgnore] * @param {Object} [opt.clipShape] */ symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) { opt = normalizeUpdateOpt(opt); function updateIncrementalAndHover(el) { if (!el.isGroup) { el.incremental = el.useHoverLayer = true; } } for (var idx = taskParams.start; idx < taskParams.end; idx++) { var point = data.getItemLayout(idx); if (symbolNeedsDraw(data, point, idx, opt)) { var el = new this._symbolCtor(data, idx, this._seriesScope); el.traverse(updateIncrementalAndHover); el.attr('position', point); this.group.add(el); data.setItemGraphicEl(idx, el); } } }; function normalizeUpdateOpt(opt) { if (opt != null && !isObject$1(opt)) { opt = {isIgnore: opt}; } return opt || {}; } symbolDrawProto.remove = function (enableAnimation) { var group = this.group; var data = this._data; // Incremental model do not have this._data. if (data && enableAnimation) { data.eachItemGraphicEl(function (el) { el.fadeOut(function () { group.remove(el); }); }); } else { group.removeAll(); } }; function makeSeriesScope(data) { var seriesModel = data.hostModel; return { itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']), hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(), symbolRotate: seriesModel.get('symbolRotate'), symbolOffset: seriesModel.get('symbolOffset'), hoverAnimation: seriesModel.get('hoverAnimation'), labelModel: seriesModel.getModel('label'), hoverLabelModel: seriesModel.getModel('emphasis.label'), cursorStyle: seriesModel.get('cursor') }; } /** * @param {Object} coordSys * @param {module:echarts/data/List} data * @param {string} valueOrigin lineSeries.option.areaStyle.origin */ function prepareDataCoordInfo(coordSys, data, valueOrigin) { var baseAxis = coordSys.getBaseAxis(); var valueAxis = coordSys.getOtherAxis(baseAxis); var valueStart = getValueStart(valueAxis, valueOrigin); var baseAxisDim = baseAxis.dim; var valueAxisDim = valueAxis.dim; var valueDim = data.mapDimension(valueAxisDim); var baseDim = data.mapDimension(baseAxisDim); var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0; var stacked = isDimensionStacked(data, valueDim, baseDim); var dataDimsForPoint = map(coordSys.dimensions, function (coordDim) { return data.mapDimension(coordDim); }); return { dataDimsForPoint: dataDimsForPoint, valueStart: valueStart, valueAxisDim: valueAxisDim, baseAxisDim: baseAxisDim, stacked: stacked, valueDim: valueDim, baseDim: baseDim, baseDataOffset: baseDataOffset, stackedOverDimension: data.getCalculationInfo('stackedOverDimension') }; } function getValueStart(valueAxis, valueOrigin) { var valueStart = 0; var extent = valueAxis.scale.getExtent(); if (valueOrigin === 'start') { valueStart = extent[0]; } else if (valueOrigin === 'end') { valueStart = extent[1]; } // auto else { // Both positive if (extent[0] > 0) { valueStart = extent[0]; } // Both negative else if (extent[1] < 0) { valueStart = extent[1]; } // If is one positive, and one negative, onZero shall be true } return valueStart; } function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) { var value = NaN; if (dataCoordInfo.stacked) { value = data.get(data.getCalculationInfo('stackedOverDimension'), idx); } if (isNaN(value)) { value = dataCoordInfo.valueStart; } var baseDataOffset = dataCoordInfo.baseDataOffset; var stackedData = []; stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx); stackedData[1 - baseDataOffset] = value; return coordSys.dataToPoint(stackedData); } // var arrayDiff = require('zrender/src/core/arrayDiff'); // 'zrender/src/core/arrayDiff' has been used before, but it did // not do well in performance when roam with fixed dataZoom window. // function convertToIntId(newIdList, oldIdList) { // // Generate int id instead of string id. // // Compare string maybe slow in score function of arrDiff // // Assume id in idList are all unique // var idIndicesMap = {}; // var idx = 0; // for (var i = 0; i < newIdList.length; i++) { // idIndicesMap[newIdList[i]] = idx; // newIdList[i] = idx++; // } // for (var i = 0; i < oldIdList.length; i++) { // var oldId = oldIdList[i]; // // Same with newIdList // if (idIndicesMap[oldId]) { // oldIdList[i] = idIndicesMap[oldId]; // } // else { // oldIdList[i] = idx++; // } // } // } function diffData(oldData, newData) { var diffResult = []; newData.diff(oldData) .add(function (idx) { diffResult.push({cmd: '+', idx: idx}); }) .update(function (newIdx, oldIdx) { diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx}); }) .remove(function (idx) { diffResult.push({cmd: '-', idx: idx}); }) .execute(); return diffResult; } var lineAnimationDiff = function ( oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin ) { var diff = diffData(oldData, newData); // var newIdList = newData.mapArray(newData.getId); // var oldIdList = oldData.mapArray(oldData.getId); // convertToIntId(newIdList, oldIdList); // // FIXME One data ? // diff = arrayDiff(oldIdList, newIdList); var currPoints = []; var nextPoints = []; // Points for stacking base line var currStackedPoints = []; var nextStackedPoints = []; var status = []; var sortedIndices = []; var rawIndices = []; var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin); for (var i = 0; i < diff.length; i++) { var diffItem = diff[i]; var pointAdded = true; // FIXME, animation is not so perfect when dataZoom window moves fast // Which is in case remvoing or add more than one data in the tail or head switch (diffItem.cmd) { case '=': var currentPt = oldData.getItemLayout(diffItem.idx); var nextPt = newData.getItemLayout(diffItem.idx1); // If previous data is NaN, use next point directly if (isNaN(currentPt[0]) || isNaN(currentPt[1])) { currentPt = nextPt.slice(); } currPoints.push(currentPt); nextPoints.push(nextPt); currStackedPoints.push(oldStackedOnPoints[diffItem.idx]); nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]); rawIndices.push(newData.getRawIndex(diffItem.idx1)); break; case '+': var idx = diffItem.idx; currPoints.push( oldCoordSys.dataToPoint([ newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx), newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx) ]) ); nextPoints.push(newData.getItemLayout(idx).slice()); currStackedPoints.push( getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx) ); nextStackedPoints.push(newStackedOnPoints[idx]); rawIndices.push(newData.getRawIndex(idx)); break; case '-': var idx = diffItem.idx; var rawIndex = oldData.getRawIndex(idx); // Data is replaced. In the case of dynamic data queue // FIXME FIXME FIXME if (rawIndex !== idx) { currPoints.push(oldData.getItemLayout(idx)); nextPoints.push(newCoordSys.dataToPoint([ oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx), oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx) ])); currStackedPoints.push(oldStackedOnPoints[idx]); nextStackedPoints.push( getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx) ); rawIndices.push(rawIndex); } else { pointAdded = false; } } // Original indices if (pointAdded) { status.push(diffItem); sortedIndices.push(sortedIndices.length); } } // Diff result may be crossed if all items are changed // Sort by data index sortedIndices.sort(function (a, b) { return rawIndices[a] - rawIndices[b]; }); var sortedCurrPoints = []; var sortedNextPoints = []; var sortedCurrStackedPoints = []; var sortedNextStackedPoints = []; var sortedStatus = []; for (var i = 0; i < sortedIndices.length; i++) { var idx = sortedIndices[i]; sortedCurrPoints[i] = currPoints[idx]; sortedNextPoints[i] = nextPoints[idx]; sortedCurrStackedPoints[i] = currStackedPoints[idx]; sortedNextStackedPoints[i] = nextStackedPoints[idx]; sortedStatus[i] = status[idx]; } return { current: sortedCurrPoints, next: sortedNextPoints, stackedOnCurrent: sortedCurrStackedPoints, stackedOnNext: sortedNextStackedPoints, status: sortedStatus }; }; // Poly path support NaN point var vec2Min = min; var vec2Max = max; var scaleAndAdd$1 = scaleAndAdd; var v2Copy = copy; // Temporary variable var v = []; var cp0 = []; var cp1 = []; function isPointNull(p) { return isNaN(p[0]) || isNaN(p[1]); } function drawSegment( ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls ) { if (smoothMonotone == null) { if (isMono(points, 'x')) { return drawMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, 'x', connectNulls); } else if (isMono(points, 'y')) { return drawMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, 'y', connectNulls); } else { return drawNonMono.apply(this, arguments); } } else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) { return drawMono.apply(this, arguments); } else { return drawNonMono.apply(this, arguments); } } /** * Check if points is in monotone. * * @param {number[][]} points Array of points which is in [x, y] form * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which * dimension that is checking. * If is 'none', `drawNonMono` should be * called. * If is undefined, either being monotone * in 'x' or 'y' will call `drawMono`. */ function isMono(points, smoothMonotone) { if (points.length <= 1) { return true; } var dim = smoothMonotone === 'x' ? 0 : 1; var last = points[0][dim]; var lastDiff = 0; for (var i = 1; i < points.length; ++i) { var diff = points[i][dim] - last; if (!isNaN(diff) && !isNaN(lastDiff) && diff !== 0 && lastDiff !== 0 && ((diff >= 0) !== (lastDiff >= 0)) ) { return false; } if (!isNaN(diff) && diff !== 0) { lastDiff = diff; last = points[i][dim]; } } return true; } /** * Draw smoothed line in monotone, in which only vertical or horizontal bezier * control points will be used. This should be used when points are monotone * either in x or y dimension. */ function drawMono( ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls ) { var prevIdx = 0; var idx = start; for (var k = 0; k < segLen; k++) { var p = points[idx]; if (idx >= allLen || idx < 0) { break; } if (isPointNull(p)) { if (connectNulls) { idx += dir; continue; } break; } if (idx === start) { ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]); } else { if (smooth > 0) { var prevP = points[prevIdx]; var dim = smoothMonotone === 'y' ? 1 : 0; // Length of control point to p, either in x or y, but not both var ctrlLen = (p[dim] - prevP[dim]) * smooth; v2Copy(cp0, prevP); cp0[dim] = prevP[dim] + ctrlLen; v2Copy(cp1, p); cp1[dim] = p[dim] - ctrlLen; ctx.bezierCurveTo( cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1] ); } else { ctx.lineTo(p[0], p[1]); } } prevIdx = idx; idx += dir; } return k; } /** * Draw smoothed line in non-monotone, in may cause undesired curve in extreme * situations. This should be used when points are non-monotone neither in x or * y dimension. */ function drawNonMono( ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls ) { var prevIdx = 0; var idx = start; for (var k = 0; k < segLen; k++) { var p = points[idx]; if (idx >= allLen || idx < 0) { break; } if (isPointNull(p)) { if (connectNulls) { idx += dir; continue; } break; } if (idx === start) { ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]); v2Copy(cp0, p); } else { if (smooth > 0) { var nextIdx = idx + dir; var nextP = points[nextIdx]; if (connectNulls) { // Find next point not null while (nextP && isPointNull(points[nextIdx])) { nextIdx += dir; nextP = points[nextIdx]; } } var ratioNextSeg = 0.5; var prevP = points[prevIdx]; var nextP = points[nextIdx]; // Last point if (!nextP || isPointNull(nextP)) { v2Copy(cp1, p); } else { // If next data is null in not connect case if (isPointNull(nextP) && !connectNulls) { nextP = p; } sub(v, nextP, prevP); var lenPrevSeg; var lenNextSeg; if (smoothMonotone === 'x' || smoothMonotone === 'y') { var dim = smoothMonotone === 'x' ? 0 : 1; lenPrevSeg = Math.abs(p[dim] - prevP[dim]); lenNextSeg = Math.abs(p[dim] - nextP[dim]); } else { lenPrevSeg = dist(p, prevP); lenNextSeg = dist(p, nextP); } // Use ratio of seg length ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg); scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg)); } // Smooth constraint vec2Min(cp0, cp0, smoothMax); vec2Max(cp0, cp0, smoothMin); vec2Min(cp1, cp1, smoothMax); vec2Max(cp1, cp1, smoothMin); ctx.bezierCurveTo( cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1] ); // cp0 of next segment scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg); } else { ctx.lineTo(p[0], p[1]); } } prevIdx = idx; idx += dir; } return k; } function getBoundingBox(points, smoothConstraint) { var ptMin = [Infinity, Infinity]; var ptMax = [-Infinity, -Infinity]; if (smoothConstraint) { for (var i = 0; i < points.length; i++) { var pt = points[i]; if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; } if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; } if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; } if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; } } } return { min: smoothConstraint ? ptMin : ptMax, max: smoothConstraint ? ptMax : ptMin }; } var Polyline$1 = Path.extend({ type: 'ec-polyline', shape: { points: [], smooth: 0, smoothConstraint: true, smoothMonotone: null, connectNulls: false }, style: { fill: null, stroke: '#000' }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var points = shape.points; var i = 0; var len$$1 = points.length; var result = getBoundingBox(points, shape.smoothConstraint); if (shape.connectNulls) { // Must remove first and last null values avoid draw error in polygon for (; len$$1 > 0; len$$1--) { if (!isPointNull(points[len$$1 - 1])) { break; } } for (; i < len$$1; i++) { if (!isPointNull(points[i])) { break; } } } while (i < len$$1) { i += drawSegment( ctx, points, i, len$$1, len$$1, 1, result.min, result.max, shape.smooth, shape.smoothMonotone, shape.connectNulls ) + 1; } } }); var Polygon$1 = Path.extend({ type: 'ec-polygon', shape: { points: [], // Offset between stacked base points and points stackedOnPoints: [], smooth: 0, stackedOnSmooth: 0, smoothConstraint: true, smoothMonotone: null, connectNulls: false }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var points = shape.points; var stackedOnPoints = shape.stackedOnPoints; var i = 0; var len$$1 = points.length; var smoothMonotone = shape.smoothMonotone; var bbox = getBoundingBox(points, shape.smoothConstraint); var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint); if (shape.connectNulls) { // Must remove first and last null values avoid draw error in polygon for (; len$$1 > 0; len$$1--) { if (!isPointNull(points[len$$1 - 1])) { break; } } for (; i < len$$1; i++) { if (!isPointNull(points[i])) { break; } } } while (i < len$$1) { var k = drawSegment( ctx, points, i, len$$1, len$$1, 1, bbox.min, bbox.max, shape.smooth, smoothMonotone, shape.connectNulls ); drawSegment( ctx, stackedOnPoints, i + k - 1, k, len$$1, -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls ); i += k + 1; ctx.closePath(); } } }); // FIXME step not support polar function isPointsSame(points1, points2) { if (points1.length !== points2.length) { return; } for (var i = 0; i < points1.length; i++) { var p1 = points1[i]; var p2 = points2[i]; if (p1[0] !== p2[0] || p1[1] !== p2[1]) { return; } } return true; } function getSmooth(smooth) { return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0); } function getAxisExtentWithGap(axis) { var extent = axis.getGlobalExtent(); if (axis.onBand) { // Remove extra 1px to avoid line miter in clipped edge var halfBandWidth = axis.getBandWidth() / 2 - 1; var dir = extent[1] > extent[0] ? 1 : -1; extent[0] += dir * halfBandWidth; extent[1] -= dir * halfBandWidth; } return extent; } /** * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys * @param {module:echarts/data/List} data * @param {Object} dataCoordInfo * @param {Array.<Array.<number>>} points */ function getStackedOnPoints(coordSys, data, dataCoordInfo) { if (!dataCoordInfo.valueDim) { return []; } var points = []; for (var idx = 0, len = data.count(); idx < len; idx++) { points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx)); } return points; } function createGridClipShape(cartesian, hasAnimation, seriesModel) { var xExtent = getAxisExtentWithGap(cartesian.getAxis('x')); var yExtent = getAxisExtentWithGap(cartesian.getAxis('y')); var isHorizontal = cartesian.getBaseAxis().isHorizontal(); var x = Math.min(xExtent[0], xExtent[1]); var y = Math.min(yExtent[0], yExtent[1]); var width = Math.max(xExtent[0], xExtent[1]) - x; var height = Math.max(yExtent[0], yExtent[1]) - y; var lineWidth = seriesModel.get('lineStyle.width') || 2; // Expand clip shape to avoid clipping when line value exceeds axis var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height); if (isHorizontal) { y -= expandSize; height += expandSize * 2; } else { x -= expandSize; width += expandSize * 2; } var clipPath = new Rect({ shape: { x: x, y: y, width: width, height: height } }); if (hasAnimation) { clipPath.shape[isHorizontal ? 'width' : 'height'] = 0; initProps(clipPath, { shape: { width: width, height: height } }, seriesModel); } return clipPath; } function createPolarClipShape(polar, hasAnimation, seriesModel) { var angleAxis = polar.getAngleAxis(); var radiusAxis = polar.getRadiusAxis(); var radiusExtent = radiusAxis.getExtent(); var angleExtent = angleAxis.getExtent(); var RADIAN = Math.PI / 180; var clipPath = new Sector({ shape: { cx: polar.cx, cy: polar.cy, r0: radiusExtent[0], r: radiusExtent[1], startAngle: -angleExtent[0] * RADIAN, endAngle: -angleExtent[1] * RADIAN, clockwise: angleAxis.inverse } }); if (hasAnimation) { clipPath.shape.endAngle = -angleExtent[0] * RADIAN; initProps(clipPath, { shape: { endAngle: -angleExtent[1] * RADIAN } }, seriesModel); } return clipPath; } function createClipShape(coordSys, hasAnimation, seriesModel) { return coordSys.type === 'polar' ? createPolarClipShape(coordSys, hasAnimation, seriesModel) : createGridClipShape(coordSys, hasAnimation, seriesModel); } function turnPointsIntoStep(points, coordSys, stepTurnAt) { var baseAxis = coordSys.getBaseAxis(); var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1; var stepPoints = []; for (var i = 0; i < points.length - 1; i++) { var nextPt = points[i + 1]; var pt = points[i]; stepPoints.push(pt); var stepPt = []; switch (stepTurnAt) { case 'end': stepPt[baseIndex] = nextPt[baseIndex]; stepPt[1 - baseIndex] = pt[1 - baseIndex]; // default is start stepPoints.push(stepPt); break; case 'middle': // default is start var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2; var stepPt2 = []; stepPt[baseIndex] = stepPt2[baseIndex] = middle; stepPt[1 - baseIndex] = pt[1 - baseIndex]; stepPt2[1 - baseIndex] = nextPt[1 - baseIndex]; stepPoints.push(stepPt); stepPoints.push(stepPt2); break; default: stepPt[baseIndex] = pt[baseIndex]; stepPt[1 - baseIndex] = nextPt[1 - baseIndex]; // default is start stepPoints.push(stepPt); } } // Last points points[i] && stepPoints.push(points[i]); return stepPoints; } function getVisualGradient(data, coordSys) { var visualMetaList = data.getVisual('visualMeta'); if (!visualMetaList || !visualMetaList.length || !data.count()) { // When data.count() is 0, gradient range can not be calculated. return; } if (coordSys.type !== 'cartesian2d') { if (__DEV__) { console.warn('Visual map on line style is only supported on cartesian2d.'); } return; } var coordDim; var visualMeta; for (var i = visualMetaList.length - 1; i >= 0; i--) { var dimIndex = visualMetaList[i].dimension; var dimName = data.dimensions[dimIndex]; var dimInfo = data.getDimensionInfo(dimName); coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y if (coordDim === 'x' || coordDim === 'y') { visualMeta = visualMetaList[i]; break; } } if (!visualMeta) { if (__DEV__) { console.warn('Visual map on line style only support x or y dimension.'); } return; } // If the area to be rendered is bigger than area defined by LinearGradient, // the canvas spec prescribes that the color of the first stop and the last // stop should be used. But if two stops are added at offset 0, in effect // browsers use the color of the second stop to render area outside // LinearGradient. So we can only infinitesimally extend area defined in // LinearGradient to render `outerColors`. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic. var colorStops = map(visualMeta.stops, function (stop) { return { coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)), color: stop.color }; }); var stopLen = colorStops.length; var outerColors = visualMeta.outerColors.slice(); if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) { colorStops.reverse(); outerColors.reverse(); } var tinyExtent = 10; // Arbitrary value: 10px var minCoord = colorStops[0].coord - tinyExtent; var maxCoord = colorStops[stopLen - 1].coord + tinyExtent; var coordSpan = maxCoord - minCoord; if (coordSpan < 1e-3) { return 'transparent'; } each$1(colorStops, function (stop) { stop.offset = (stop.coord - minCoord) / coordSpan; }); colorStops.push({ offset: stopLen ? colorStops[stopLen - 1].offset : 0.5, color: outerColors[1] || 'transparent' }); colorStops.unshift({ // notice colorStops.length have been changed. offset: stopLen ? colorStops[0].offset : 0.5, color: outerColors[0] || 'transparent' }); // zrUtil.each(colorStops, function (colorStop) { // // Make sure each offset has rounded px to avoid not sharp edge // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start); // }); var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true); gradient[coordDim] = minCoord; gradient[coordDim + '2'] = maxCoord; return gradient; } Chart.extend({ type: 'line', init: function () { var lineGroup = new Group(); var symbolDraw = new SymbolDraw(); this.group.add(symbolDraw.group); this._symbolDraw = symbolDraw; this._lineGroup = lineGroup; }, render: function (seriesModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var group = this.group; var data = seriesModel.getData(); var lineStyleModel = seriesModel.getModel('lineStyle'); var areaStyleModel = seriesModel.getModel('areaStyle'); var points = data.mapArray(data.getItemLayout); var isCoordSysPolar = coordSys.type === 'polar'; var prevCoordSys = this._coordSys; var symbolDraw = this._symbolDraw; var polyline = this._polyline; var polygon = this._polygon; var lineGroup = this._lineGroup; var hasAnimation = seriesModel.get('animation'); var isAreaChart = !areaStyleModel.isEmpty(); var valueOrigin = areaStyleModel.get('origin'); var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin); var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo); var showSymbol = seriesModel.get('showSymbol'); var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol') && this._getSymbolIgnoreFunc(data, coordSys); // Remove temporary symbols var oldData = this._data; oldData && oldData.eachItemGraphicEl(function (el, idx) { if (el.__temp) { group.remove(el); oldData.setItemGraphicEl(idx, null); } }); // Remove previous created symbols if showSymbol changed to false if (!showSymbol) { symbolDraw.remove(); } group.add(lineGroup); // FIXME step not support polar var step = !isCoordSysPolar && seriesModel.get('step'); // Initialization animation or coordinate system changed if ( !(polyline && prevCoordSys.type === coordSys.type && step === this._step) ) { showSymbol && symbolDraw.updateData(data, { isIgnore: isSymbolIgnore, clipShape: createClipShape(coordSys, false, seriesModel) }); if (step) { // TODO If stacked series is not step points = turnPointsIntoStep(points, coordSys, step); stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step); } polyline = this._newPolyline(points, coordSys, hasAnimation); if (isAreaChart) { polygon = this._newPolygon( points, stackedOnPoints, coordSys, hasAnimation ); } lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel)); } else { if (isAreaChart && !polygon) { // If areaStyle is added polygon = this._newPolygon( points, stackedOnPoints, coordSys, hasAnimation ); } else if (polygon && !isAreaChart) { // If areaStyle is removed lineGroup.remove(polygon); polygon = this._polygon = null; } var coordSysClipShape = createClipShape(coordSys, false, seriesModel); // Update clipPath lineGroup.setClipPath(coordSysClipShape); // Always update, or it is wrong in the case turning on legend // because points are not changed showSymbol && symbolDraw.updateData(data, { isIgnore: isSymbolIgnore, clipShape: coordSysClipShape }); // Stop symbol animation and sync with line points // FIXME performance? data.eachItemGraphicEl(function (el) { el.stopAnimation(true); }); // In the case data zoom triggerred refreshing frequently // Data may not change if line has a category axis. So it should animate nothing if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points) ) { if (hasAnimation) { this._updateAnimation( data, stackedOnPoints, coordSys, api, step, valueOrigin ); } else { // Not do it in update with animation if (step) { // TODO If stacked series is not step points = turnPointsIntoStep(points, coordSys, step); stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step); } polyline.setShape({ points: points }); polygon && polygon.setShape({ points: points, stackedOnPoints: stackedOnPoints }); } } } var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color'); polyline.useStyle(defaults( // Use color in lineStyle first lineStyleModel.getLineStyle(), { fill: 'none', stroke: visualColor, lineJoin: 'bevel' } )); var smooth = seriesModel.get('smooth'); smooth = getSmooth(seriesModel.get('smooth')); polyline.setShape({ smooth: smooth, smoothMonotone: seriesModel.get('smoothMonotone'), connectNulls: seriesModel.get('connectNulls') }); if (polygon) { var stackedOnSeries = data.getCalculationInfo('stackedOnSeries'); var stackedOnSmooth = 0; polygon.useStyle(defaults( areaStyleModel.getAreaStyle(), { fill: visualColor, opacity: 0.7, lineJoin: 'bevel' } )); if (stackedOnSeries) { stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth')); } polygon.setShape({ smooth: smooth, stackedOnSmooth: stackedOnSmooth, smoothMonotone: seriesModel.get('smoothMonotone'), connectNulls: seriesModel.get('connectNulls') }); } this._data = data; // Save the coordinate system for transition animation when data changed this._coordSys = coordSys; this._stackedOnPoints = stackedOnPoints; this._points = points; this._step = step; this._valueOrigin = valueOrigin; }, dispose: function () {}, highlight: function (seriesModel, ecModel, api, payload) { var data = seriesModel.getData(); var dataIndex = queryDataIndex(data, payload); if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) { var symbol = data.getItemGraphicEl(dataIndex); if (!symbol) { // Create a temporary symbol if it is not exists var pt = data.getItemLayout(dataIndex); if (!pt) { // Null data return; } symbol = new SymbolClz(data, dataIndex); symbol.position = pt; symbol.setZ( seriesModel.get('zlevel'), seriesModel.get('z') ); symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]); symbol.__temp = true; data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation symbol.stopSymbolAnimation(true); this.group.add(symbol); } symbol.highlight(); } else { // Highlight whole series Chart.prototype.highlight.call( this, seriesModel, ecModel, api, payload ); } }, downplay: function (seriesModel, ecModel, api, payload) { var data = seriesModel.getData(); var dataIndex = queryDataIndex(data, payload); if (dataIndex != null && dataIndex >= 0) { var symbol = data.getItemGraphicEl(dataIndex); if (symbol) { if (symbol.__temp) { data.setItemGraphicEl(dataIndex, null); this.group.remove(symbol); } else { symbol.downplay(); } } } else { // FIXME // can not downplay completely. // Downplay whole series Chart.prototype.downplay.call( this, seriesModel, ecModel, api, payload ); } }, /** * @param {module:zrender/container/Group} group * @param {Array.<Array.<number>>} points * @private */ _newPolyline: function (points) { var polyline = this._polyline; // Remove previous created polyline if (polyline) { this._lineGroup.remove(polyline); } polyline = new Polyline$1({ shape: { points: points }, silent: true, z2: 10 }); this._lineGroup.add(polyline); this._polyline = polyline; return polyline; }, /** * @param {module:zrender/container/Group} group * @param {Array.<Array.<number>>} stackedOnPoints * @param {Array.<Array.<number>>} points * @private */ _newPolygon: function (points, stackedOnPoints) { var polygon = this._polygon; // Remove previous created polygon if (polygon) { this._lineGroup.remove(polygon); } polygon = new Polygon$1({ shape: { points: points, stackedOnPoints: stackedOnPoints }, silent: true }); this._lineGroup.add(polygon); this._polygon = polygon; return polygon; }, /** * @private */ _getSymbolIgnoreFunc: function (data, coordSys) { var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; // `getLabelInterval` is provided by echarts/component/axis if (categoryAxis && categoryAxis.isLabelIgnored) { return bind(categoryAxis.isLabelIgnored, categoryAxis); } }, /** * @private */ // FIXME Two value axis _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) { var polyline = this._polyline; var polygon = this._polygon; var seriesModel = data.hostModel; var diff = lineAnimationDiff( this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin ); var current = diff.current; var stackedOnCurrent = diff.stackedOnCurrent; var next = diff.next; var stackedOnNext = diff.stackedOnNext; if (step) { // TODO If stacked series is not step current = turnPointsIntoStep(diff.current, coordSys, step); stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step); next = turnPointsIntoStep(diff.next, coordSys, step); stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step); } // `diff.current` is subset of `current` (which should be ensured by // turnPointsIntoStep), so points in `__points` can be updated when // points in `current` are update during animation. polyline.shape.__points = diff.current; polyline.shape.points = current; updateProps(polyline, { shape: { points: next } }, seriesModel); if (polygon) { polygon.setShape({ points: current, stackedOnPoints: stackedOnCurrent }); updateProps(polygon, { shape: { points: next, stackedOnPoints: stackedOnNext } }, seriesModel); } var updatedDataInfo = []; var diffStatus = diff.status; for (var i = 0; i < diffStatus.length; i++) { var cmd = diffStatus[i].cmd; if (cmd === '=') { var el = data.getItemGraphicEl(diffStatus[i].idx1); if (el) { updatedDataInfo.push({ el: el, ptIdx: i // Index of points }); } } } if (polyline.animators && polyline.animators.length) { polyline.animators[0].during(function () { for (var i = 0; i < updatedDataInfo.length; i++) { var el = updatedDataInfo[i].el; el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]); } }); } }, remove: function (ecModel) { var group = this.group; var oldData = this._data; this._lineGroup.removeAll(); this._symbolDraw.remove(true); // Remove temporary created elements when highlighting oldData && oldData.eachItemGraphicEl(function (el, idx) { if (el.__temp) { group.remove(el); oldData.setItemGraphicEl(idx, null); } }); this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._data = null; } }); var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) { // Encoding visual for all series include which is filtered for legend drawing return { seriesType: seriesType, performRawSeries: true, reset: function (seriesModel, ecModel, api) { var data = seriesModel.getData(); var symbolType = seriesModel.get('symbol') || defaultSymbolType; var symbolSize = seriesModel.get('symbolSize'); data.setVisual({ legendSymbol: legendSymbol || symbolType, symbol: symbolType, symbolSize: symbolSize }); // Only visible series has each data be visual encoded if (ecModel.isSeriesFiltered(seriesModel)) { return; } var hasCallback = typeof symbolSize === 'function'; function dataEach(data, idx) { if (typeof symbolSize === 'function') { var rawValue = seriesModel.getRawValue(idx); // FIXME var params = seriesModel.getDataParams(idx); data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params)); } if (data.hasItemOption) { var itemModel = data.getItemModel(idx); var itemSymbolType = itemModel.getShallow('symbol', true); var itemSymbolSize = itemModel.getShallow('symbolSize', true); // If has item symbol if (itemSymbolType != null) { data.setItemVisual(idx, 'symbol', itemSymbolType); } if (itemSymbolSize != null) { // PENDING Transform symbolSize ? data.setItemVisual(idx, 'symbolSize', itemSymbolSize); } } } return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null }; } }; }; var layoutPoints = function (seriesType) { return { seriesType: seriesType, plan: createRenderPlanner(), reset: function (seriesModel) { var data = seriesModel.getData(); var coordSys = seriesModel.coordinateSystem; var pipelineContext = seriesModel.pipelineContext; var isLargeRender = pipelineContext.large; if (!coordSys) { return; } var dims = map(coordSys.dimensions, function (dim) { return data.mapDimension(dim); }).slice(0, 2); var dimLen = dims.length; if (isDimensionStacked(data, dims[0], dims[1])) { dims[0] = data.getCalculationInfo('stackResultDimension'); } if (isDimensionStacked(data, dims[1], dims[0])) { dims[1] = data.getCalculationInfo('stackResultDimension'); } function progress(params, data) { var segCount = params.end - params.start; var points = isLargeRender && new Float32Array(segCount * dimLen); for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) { var point; if (dimLen === 1) { var x = data.get(dims[0], i, true); point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut); } else { var x = tmpIn[0] = data.get(dims[0], i, true); var y = tmpIn[1] = data.get(dims[1], i, true); // Also {Array.<number>}, not undefined to avoid if...else... statement point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut); } if (isLargeRender) { points[offset++] = point ? point[0] : NaN; points[offset++] = point ? point[1] : NaN; } else { data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]); } } isLargeRender && data.setLayout('symbolPoints', points); } return dimLen && {progress: progress}; } }; }; var samplers = { average: function (frame) { var sum = 0; var count = 0; for (var i = 0; i < frame.length; i++) { if (!isNaN(frame[i])) { sum += frame[i]; count++; } } // Return NaN if count is 0 return count === 0 ? NaN : sum / count; }, sum: function (frame) { var sum = 0; for (var i = 0; i < frame.length; i++) { // Ignore NaN sum += frame[i] || 0; } return sum; }, max: function (frame) { var max = -Infinity; for (var i = 0; i < frame.length; i++) { frame[i] > max && (max = frame[i]); } return max; }, min: function (frame) { var min = Infinity; for (var i = 0; i < frame.length; i++) { frame[i] < min && (min = frame[i]); } return min; }, // TODO // Median nearest: function (frame) { return frame[0]; } }; var indexSampler = function (frame, value) { return Math.round(frame.length / 2); }; var dataSample = function (seriesType) { return { seriesType: seriesType, reset: function (seriesModel, ecModel, api) { var data = seriesModel.getData(); var sampling = seriesModel.get('sampling'); var coordSys = seriesModel.coordinateSystem; // Only cartesian2d support down sampling if (coordSys.type === 'cartesian2d' && sampling) { var baseAxis = coordSys.getBaseAxis(); var valueAxis = coordSys.getOtherAxis(baseAxis); var extent = baseAxis.getExtent(); // Coordinste system has been resized var size = extent[1] - extent[0]; var rate = Math.round(data.count() / size); if (rate > 1) { var sampler; if (typeof sampling === 'string') { sampler = samplers[sampling]; } else if (typeof sampling === 'function') { sampler = sampling; } if (sampler) { seriesModel.setData(data.downSample( valueAxis.dim, 1 / rate, sampler, indexSampler )); } } } } }; }; /** * // Scale class management * @module echarts/scale/Scale */ /** * @param {Object} [setting] */ function Scale(setting) { this._setting = setting || {}; /** * Extent * @type {Array.<number>} * @protected */ this._extent = [Infinity, -Infinity]; /** * Step is calculated in adjustExtent * @type {Array.<number>} * @protected */ this._interval = 0; this.init && this.init.apply(this, arguments); } /** * Parse input val to valid inner number. * @param {*} val * @return {number} */ Scale.prototype.parse = function (val) { // Notice: This would be a trap here, If the implementation // of this method depends on extent, and this method is used // before extent set (like in dataZoom), it would be wrong. // Nevertheless, parse does not depend on extent generally. return val; }; Scale.prototype.getSetting = function (name) { return this._setting[name]; }; Scale.prototype.contain = function (val) { var extent = this._extent; return val >= extent[0] && val <= extent[1]; }; /** * Normalize value to linear [0, 1], return 0.5 if extent span is 0 * @param {number} val * @return {number} */ Scale.prototype.normalize = function (val) { var extent = this._extent; if (extent[1] === extent[0]) { return 0.5; } return (val - extent[0]) / (extent[1] - extent[0]); }; /** * Scale normalized value * @param {number} val * @return {number} */ Scale.prototype.scale = function (val) { var extent = this._extent; return val * (extent[1] - extent[0]) + extent[0]; }; /** * Set extent from data * @param {Array.<number>} other */ Scale.prototype.unionExtent = function (other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]); other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power // this.setExtent(extent[0], extent[1]); }; /** * Set extent from data * @param {module:echarts/data/List} data * @param {string} dim */ Scale.prototype.unionExtentFromData = function (data, dim) { this.unionExtent(data.getApproximateExtent(dim)); }; /** * Get extent * @return {Array.<number>} */ Scale.prototype.getExtent = function () { return this._extent.slice(); }; /** * Set extent * @param {number} start * @param {number} end */ Scale.prototype.setExtent = function (start, end) { var thisExtent = this._extent; if (!isNaN(start)) { thisExtent[0] = start; } if (!isNaN(end)) { thisExtent[1] = end; } }; /** * @return {Array.<string>} */ Scale.prototype.getTicksLabels = function () { var labels = []; var ticks = this.getTicks(); for (var i = 0; i < ticks.length; i++) { labels.push(this.getLabel(ticks[i])); } return labels; }; /** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */ Scale.prototype.isBlank = function () { return this._isBlank; }, /** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */ Scale.prototype.setBlank = function (isBlank) { this._isBlank = isBlank; }; enableClassExtend(Scale); enableClassManagement(Scale, { registerWhenExtend: true }); /** * @constructor * @param {Object} [opt] * @param {Object} [opt.categories=[]] * @param {Object} [opt.needCollect=false] * @param {Object} [opt.deduplication=false] */ function OrdinalMeta(opt) { /** * @readOnly * @type {Array.<string>} */ this.categories = opt.categories || []; /** * @private * @type {boolean} */ this._needCollect = opt.needCollect; /** * @private * @type {boolean} */ this._deduplication = opt.deduplication; /** * @private * @type {boolean} */ this._map; } /** * @param {module:echarts/model/Model} axisModel * @return {module:echarts/data/OrdinalMeta} */ OrdinalMeta.createByAxisModel = function (axisModel) { var option = axisModel.option; var data = option.data; var categories = data && map(data, getName); return new OrdinalMeta({ categories: categories, needCollect: !categories, // deduplication is default in axis. deduplication: option.dedplication !== false }); }; var proto$1 = OrdinalMeta.prototype; /** * @param {string} category * @return {number} ordinal */ proto$1.getOrdinal = function (category) { return getOrCreateMap(this).get(category); }; /** * @param {*} category * @return {number} The ordinal. If not found, return NaN. */ proto$1.parseAndCollect = function (category) { var index; var needCollect = this._needCollect; // The value of category dim can be the index of the given category set. // This feature is only supported when !needCollect, because we should // consider a common case: a value is 2017, which is a number but is // expected to be tread as a category. This case usually happen in dataset, // where it happent to be no need of the index feature. if (typeof category !== 'string' && !needCollect) { return category; } // Optimize for the scenario: // category is ['2012-01-01', '2012-01-02', ...], where the input // data has been ensured not duplicate and is large data. // Notice, if a dataset dimension provide categroies, usually echarts // should remove duplication except user tell echarts dont do that // (set axis.deduplication = false), because echarts do not know whether // the values in the category dimension has duplication (consider the // parallel-aqi example) if (needCollect && !this._deduplication) { index = this.categories.length; this.categories[index] = category; return index; } var map$$1 = getOrCreateMap(this); index = map$$1.get(category); if (index == null) { if (needCollect) { index = this.categories.length; this.categories[index] = category; map$$1.set(category, index); } else { index = NaN; } } return index; }; // Consider big data, do not create map until needed. function getOrCreateMap(ordinalMeta) { return ordinalMeta._map || ( ordinalMeta._map = createHashMap(ordinalMeta.categories) ); } function getName(obj) { if (isObject$1(obj) && obj.value != null) { return obj.value; } else { return obj + ''; } } /** * Linear continuous scale * @module echarts/coord/scale/Ordinal * * http://en.wikipedia.org/wiki/Level_of_measurement */ // FIXME only one data var scaleProto = Scale.prototype; var OrdinalScale = Scale.extend({ type: 'ordinal', /** * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta */ init: function (ordinalMeta, extent) { // Caution: Should not use instanceof, consider ec-extensions using // import approach to get OrdinalMeta class. if (!ordinalMeta || isArray(ordinalMeta)) { ordinalMeta = new OrdinalMeta({categories: ordinalMeta}); } this._ordinalMeta = ordinalMeta; this._extent = extent || [0, ordinalMeta.categories.length - 1]; }, parse: function (val) { return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float. : Math.round(val); }, contain: function (rank) { rank = this.parse(rank); return scaleProto.contain.call(this, rank) && this._ordinalMeta.categories[rank] != null; }, /** * Normalize given rank or name to linear [0, 1] * @param {number|string} [val] * @return {number} */ normalize: function (val) { return scaleProto.normalize.call(this, this.parse(val)); }, scale: function (val) { return Math.round(scaleProto.scale.call(this, val)); }, /** * @return {Array} */ getTicks: function () { var ticks = []; var extent = this._extent; var rank = extent[0]; while (rank <= extent[1]) { ticks.push(rank); rank++; } return ticks; }, /** * Get item on rank n * @param {number} n * @return {string} */ getLabel: function (n) { return this._ordinalMeta.categories[n]; }, /** * @return {number} */ count: function () { return this._extent[1] - this._extent[0] + 1; }, /** * @override */ unionExtentFromData: function (data, dim) { this.unionExtent(data.getApproximateExtent(dim)); }, niceTicks: noop, niceExtent: noop }); /** * @return {module:echarts/scale/Time} */ OrdinalScale.create = function () { return new OrdinalScale(); }; /** * For testable. */ var roundNumber$1 = round$1; /** * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number. * Should be extent[0] < extent[1]. * @param {number} splitNumber splitNumber should be >= 1. * @param {number} [minInterval] * @param {number} [maxInterval] * @return {Object} {interval, intervalPrecision, niceTickExtent} */ function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) { var result = {}; var span = extent[1] - extent[0]; var interval = result.interval = nice(span / splitNumber, true); if (minInterval != null && interval < minInterval) { interval = result.interval = minInterval; } if (maxInterval != null && interval > maxInterval) { interval = result.interval = maxInterval; } // Tow more digital for tick. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent var niceTickExtent = result.niceTickExtent = [ roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision), roundNumber$1(Math.floor(extent[1] / interval) * interval, precision) ]; fixExtent(niceTickExtent, extent); return result; } /** * @param {number} interval * @return {number} interval precision */ function getIntervalPrecision(interval) { // Tow more digital for tick. return getPrecisionSafe(interval) + 2; } function clamp(niceTickExtent, idx, extent) { niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]); } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent. function fixExtent(niceTickExtent, extent) { !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]); !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]); clamp(niceTickExtent, 0, extent); clamp(niceTickExtent, 1, extent); if (niceTickExtent[0] > niceTickExtent[1]) { niceTickExtent[0] = niceTickExtent[1]; } } function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) { var ticks = []; // If interval is 0, return []; if (!interval) { return ticks; } // Consider this case: using dataZoom toolbox, zoom and zoom. var safeLimit = 10000; if (extent[0] < niceTickExtent[0]) { ticks.push(extent[0]); } var tick = niceTickExtent[0]; while (tick <= niceTickExtent[1]) { ticks.push(tick); // Avoid rounding error tick = roundNumber$1(tick + interval, intervalPrecision); if (tick === ticks[ticks.length - 1]) { // Consider out of safe float point, e.g., // -3711126.9907707 + 2e-10 === -3711126.9907707 break; } if (ticks.length > safeLimit) { return []; } } // Consider this case: the last item of ticks is smaller // than niceTickExtent[1] and niceTickExtent[1] === extent[1]. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) { ticks.push(extent[1]); } return ticks; } /** * Interval scale * @module echarts/scale/Interval */ var roundNumber = round$1; /** * @alias module:echarts/coord/scale/Interval * @constructor */ var IntervalScale = Scale.extend({ type: 'interval', _interval: 0, _intervalPrecision: 2, setExtent: function (start, end) { var thisExtent = this._extent; //start,end may be a Number like '25',so... if (!isNaN(start)) { thisExtent[0] = parseFloat(start); } if (!isNaN(end)) { thisExtent[1] = parseFloat(end); } }, unionExtent: function (other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]); other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]); }, /** * Get interval */ getInterval: function () { return this._interval; }, /** * Set interval */ setInterval: function (interval) { this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent // We assume user wan't to set both interval, min, max to get a better result this._niceExtent = this._extent.slice(); this._intervalPrecision = getIntervalPrecision(interval); }, /** * @return {Array.<number>} */ getTicks: function () { return intervalScaleGetTicks( this._interval, this._extent, this._niceExtent, this._intervalPrecision ); }, /** * @return {Array.<string>} */ getTicksLabels: function () { var labels = []; var ticks = this.getTicks(); for (var i = 0; i < ticks.length; i++) { labels.push(this.getLabel(ticks[i])); } return labels; }, /** * @param {number} data * @param {Object} [opt] * @param {number|string} [opt.precision] If 'auto', use nice presision. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2. * @return {string} */ getLabel: function (data, opt) { if (data == null) { return ''; } var precision = opt && opt.precision; if (precision == null) { precision = getPrecisionSafe(data) || 0; } else if (precision === 'auto') { // Should be more precise then tick. precision = this._intervalPrecision; } // (1) If `precision` is set, 12.005 should be display as '12.00500'. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'. data = roundNumber(data, precision, true); return addCommas(data); }, /** * Update interval and extent of intervals for nice ticks * * @param {number} [splitNumber = 5] Desired number of ticks * @param {number} [minInterval] * @param {number} [maxInterval] */ niceTicks: function (splitNumber, minInterval, maxInterval) { splitNumber = splitNumber || 5; var extent = this._extent; var span = extent[1] - extent[0]; if (!isFinite(span)) { return; } // User may set axis min 0 and data are all negative // FIXME If it needs to reverse ? if (span < 0) { span = -span; extent.reverse(); } var result = intervalScaleNiceTicks( extent, splitNumber, minInterval, maxInterval ); this._intervalPrecision = result.intervalPrecision; this._interval = result.interval; this._niceExtent = result.niceTickExtent; }, /** * Nice extent. * @param {Object} opt * @param {number} [opt.splitNumber = 5] Given approx tick number * @param {boolean} [opt.fixMin=false] * @param {boolean} [opt.fixMax=false] * @param {boolean} [opt.minInterval] * @param {boolean} [opt.maxInterval] */ niceExtent: function (opt) { var extent = this._extent; // If extent start and end are same, expand them if (extent[0] === extent[1]) { if (extent[0] !== 0) { // Expand extent var expandSize = extent[0]; // In the fowllowing case // Axis has been fixed max 100 // Plus data are all 100 and axis extent are [100, 100]. // Extend to the both side will cause expanded max is larger than fixed max. // So only expand to the smaller side. if (!opt.fixMax) { extent[1] += expandSize / 2; extent[0] -= expandSize / 2; } else { extent[0] -= expandSize / 2; } } else { extent[1] = 1; } } var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity] if (!isFinite(span)) { extent[0] = 0; extent[1] = 1; } this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent; var interval = this._interval; if (!opt.fixMin) { extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval); } if (!opt.fixMax) { extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval); } } }); /** * @return {module:echarts/scale/Time} */ IntervalScale.create = function () { return new IntervalScale(); }; var STACK_PREFIX = '__ec_stack_'; function getSeriesStackId(seriesModel) { return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex; } function getAxisKey(axis) { return axis.dim + axis.index; } /** * @param {Object} opt * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently. * @param {number} opt.count Positive interger. * @param {number} [opt.barWidth] * @param {number} [opt.barMaxWidth] * @param {number} [opt.barGap] * @param {number} [opt.barCategoryGap] * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined. */ function calBarWidthAndOffset(barSeries, api) { var seriesInfoList = map(barSeries, function (seriesModel) { var data = seriesModel.getData(); var cartesian = seriesModel.coordinateSystem; var baseAxis = cartesian.getBaseAxis(); var axisExtent = baseAxis.getExtent(); var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count()); var barWidth = parsePercent$1( seriesModel.get('barWidth'), bandWidth ); var barMaxWidth = parsePercent$1( seriesModel.get('barMaxWidth'), bandWidth ); var barGap = seriesModel.get('barGap'); var barCategoryGap = seriesModel.get('barCategoryGap'); return { bandWidth: bandWidth, barWidth: barWidth, barMaxWidth: barMaxWidth, barGap: barGap, barCategoryGap: barCategoryGap, axisKey: getAxisKey(baseAxis), stackId: getSeriesStackId(seriesModel) }; }); return doCalBarWidthAndOffset(seriesInfoList, api); } function doCalBarWidthAndOffset(seriesInfoList, api) { // Columns info on each category axis. Key is cartesian name var columnsMap = {}; each$1(seriesInfoList, function (seriesInfo, idx) { var axisKey = seriesInfo.axisKey; var bandWidth = seriesInfo.bandWidth; var columnsOnAxis = columnsMap[axisKey] || { bandWidth: bandWidth, remainedWidth: bandWidth, autoWidthCount: 0, categoryGap: '20%', gap: '30%', stacks: {} }; var stacks = columnsOnAxis.stacks; columnsMap[axisKey] = columnsOnAxis; var stackId = seriesInfo.stackId; if (!stacks[stackId]) { columnsOnAxis.autoWidthCount++; } stacks[stackId] = stacks[stackId] || { width: 0, maxWidth: 0 }; // Caution: In a single coordinate system, these barGrid attributes // will be shared by series. Consider that they have default values, // only the attributes set on the last series will work. // Do not change this fact unless there will be a break change. // TODO var barWidth = seriesInfo.barWidth; if (barWidth && !stacks[stackId].width) { // See #6312, do not restrict width. stacks[stackId].width = barWidth; barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth); columnsOnAxis.remainedWidth -= barWidth; } var barMaxWidth = seriesInfo.barMaxWidth; barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth); var barGap = seriesInfo.barGap; (barGap != null) && (columnsOnAxis.gap = barGap); var barCategoryGap = seriesInfo.barCategoryGap; (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap); }); var result = {}; each$1(columnsMap, function (columnsOnAxis, coordSysName) { result[coordSysName] = {}; var stacks = columnsOnAxis.stacks; var bandWidth = columnsOnAxis.bandWidth; var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth); var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1); var remainedWidth = columnsOnAxis.remainedWidth; var autoWidthCount = columnsOnAxis.autoWidthCount; var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth each$1(stacks, function (column, stack) { var maxWidth = column.maxWidth; if (maxWidth && maxWidth < autoWidth) { maxWidth = Math.min(maxWidth, remainedWidth); if (column.width) { maxWidth = Math.min(maxWidth, column.width); } remainedWidth -= maxWidth; column.width = maxWidth; autoWidthCount--; } }); // Recalculate width again autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0); var widthSum = 0; var lastColumn; each$1(stacks, function (column, idx) { if (!column.width) { column.width = autoWidth; } lastColumn = column; widthSum += column.width * (1 + barGapPercent); }); if (lastColumn) { widthSum -= lastColumn.width * barGapPercent; } var offset = -widthSum / 2; each$1(stacks, function (column, stackId) { result[coordSysName][stackId] = result[coordSysName][stackId] || { offset: offset, width: column.width }; offset += column.width * (1 + barGapPercent); }); }); return result; } /** * @param {string} seriesType * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ function layout(seriesType, ecModel, api) { var seriesModels = []; ecModel.eachSeriesByType(seriesType, function (seriesModel) { // Check series coordinate, do layout for cartesian2d only if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') { seriesModels.push(seriesModel); } }); var barWidthAndOffset = calBarWidthAndOffset(seriesModels); var lastStackCoords = {}; each$1(seriesModels, function (seriesModel) { var data = seriesModel.getData(); var cartesian = seriesModel.coordinateSystem; var baseAxis = cartesian.getBaseAxis(); var stackId = getSeriesStackId(seriesModel); var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId]; var columnOffset = columnLayoutInfo.offset; var columnWidth = columnLayoutInfo.width; var valueAxis = cartesian.getOtherAxis(baseAxis); var barMinHeight = seriesModel.get('barMinHeight') || 0; lastStackCoords[stackId] = lastStackCoords[stackId] || []; data.setLayout({ offset: columnOffset, size: columnWidth }); var valueDim = data.mapDimension(valueAxis.dim); var baseDim = data.mapDimension(baseAxis.dim); var stacked = isDimensionStacked(data, valueDim, baseDim); var isValueAxisH = valueAxis.isHorizontal(); var valueAxisStart = (baseAxis.onZero || stacked) ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0)) : valueAxis.getGlobalExtent()[0]; for (var idx = 0, len = data.count(); idx < len; idx++) { var value = data.get(valueDim, idx); var baseValue = data.get(baseDim, idx); if (isNaN(value)) { continue; } var sign = value >= 0 ? 'p' : 'n'; var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in // stackResultDimension directly. if (stacked) { // Only ordinal axis can be stacked. if (!lastStackCoords[stackId][baseValue]) { lastStackCoords[stackId][baseValue] = { p: valueAxisStart, // Positive stack n: valueAxisStart // Negative stack }; } // Should also consider #4243 baseCoord = lastStackCoords[stackId][baseValue][sign]; } var x; var y; var width; var height; if (isValueAxisH) { var coord = cartesian.dataToPoint([value, baseValue]); x = baseCoord; y = coord[1] + columnOffset; width = coord[0] - valueAxisStart; height = columnWidth; if (Math.abs(width) < barMinHeight) { width = (width < 0 ? -1 : 1) * barMinHeight; } stacked && (lastStackCoords[stackId][baseValue][sign] += width); } else { var coord = cartesian.dataToPoint([baseValue, value]); x = coord[0] + columnOffset; y = baseCoord; width = columnWidth; height = coord[1] - valueAxisStart; if (Math.abs(height) < barMinHeight) { // Include zero to has a positive bar height = (height <= 0 ? -1 : 1) * barMinHeight; } stacked && (lastStackCoords[stackId][baseValue][sign] += height); } data.setItemLayout(idx, { x: x, y: y, width: width, height: height }); } }, this); } // [About UTC and local time zone]: // In most cases, `number.parseDate` will treat input data string as local time // (except time zone is specified in time string). And `format.formateTime` returns // local time by default. option.useUTC is false by default. This design have // concidered these common case: // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed // in local time by default. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed // as its original time, without any time difference. var intervalScaleProto = IntervalScale.prototype; var mathCeil = Math.ceil; var mathFloor = Math.floor; var ONE_SECOND = 1000; var ONE_MINUTE = ONE_SECOND * 60; var ONE_HOUR = ONE_MINUTE * 60; var ONE_DAY = ONE_HOUR * 24; // FIXME 公用? var bisect = function (a, x, lo, hi) { while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid][1] < x) { lo = mid + 1; } else { hi = mid; } } return lo; }; /** * @alias module:echarts/coord/scale/Time * @constructor */ var TimeScale = IntervalScale.extend({ type: 'time', /** * @override */ getLabel: function (val) { var stepLvl = this._stepLvl; var date = new Date(val); return formatTime(stepLvl[0], date, this.getSetting('useUTC')); }, /** * @override */ niceExtent: function (opt) { var extent = this._extent; // If extent start and end are same, expand them if (extent[0] === extent[1]) { // Expand extent extent[0] -= ONE_DAY; extent[1] += ONE_DAY; } // If there are no data and extent are [Infinity, -Infinity] if (extent[1] === -Infinity && extent[0] === Infinity) { var d = new Date(); extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate()); extent[0] = extent[1] - ONE_DAY; } this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent; var interval = this._interval; if (!opt.fixMin) { extent[0] = round$1(mathFloor(extent[0] / interval) * interval); } if (!opt.fixMax) { extent[1] = round$1(mathCeil(extent[1] / interval) * interval); } }, /** * @override */ niceTicks: function (approxTickNum, minInterval, maxInterval) { approxTickNum = approxTickNum || 10; var extent = this._extent; var span = extent[1] - extent[0]; var approxInterval = span / approxTickNum; if (minInterval != null && approxInterval < minInterval) { approxInterval = minInterval; } if (maxInterval != null && approxInterval > maxInterval) { approxInterval = maxInterval; } var scaleLevelsLen = scaleLevels.length; var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen); var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)]; var interval = level[1]; // Same with interval scale if span is much larger than 1 year if (level[0] === 'year') { var yearSpan = span / interval; // From "Nice Numbers for Graph Labels" of Graphic Gems // var niceYearSpan = numberUtil.nice(yearSpan, false); var yearStep = nice(yearSpan / approxTickNum, true); interval *= yearStep; } var timezoneOffset = this.getSetting('useUTC') ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000; var niceExtent = [ Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset), Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset) ]; fixExtent(niceExtent, extent); this._stepLvl = level; // Interval will be used in getTicks this._interval = interval; this._niceExtent = niceExtent; }, parse: function (val) { // val might be float. return +parseDate(val); } }); each$1(['contain', 'normalize'], function (methodName) { TimeScale.prototype[methodName] = function (val) { return intervalScaleProto[methodName].call(this, this.parse(val)); }; }); // Steps from d3 var scaleLevels = [ // Format interval ['hh:mm:ss', ONE_SECOND], // 1s ['hh:mm:ss', ONE_SECOND * 5], // 5s ['hh:mm:ss', ONE_SECOND * 10], // 10s ['hh:mm:ss', ONE_SECOND * 15], // 15s ['hh:mm:ss', ONE_SECOND * 30], // 30s ['hh:mm\nMM-dd', ONE_MINUTE], // 1m ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m ['hh:mm\nMM-dd', ONE_HOUR], // 1h ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h ['MM-dd\nyyyy', ONE_DAY], // 1d ['MM-dd\nyyyy', ONE_DAY * 2], // 2d ['MM-dd\nyyyy', ONE_DAY * 3], // 3d ['MM-dd\nyyyy', ONE_DAY * 4], // 4d ['MM-dd\nyyyy', ONE_DAY * 5], // 5d ['MM-dd\nyyyy', ONE_DAY * 6], // 6d ['week', ONE_DAY * 7], // 7d ['MM-dd\nyyyy', ONE_DAY * 10], // 10d ['week', ONE_DAY * 14], // 2w ['week', ONE_DAY * 21], // 3w ['month', ONE_DAY * 31], // 1M ['week', ONE_DAY * 42], // 6w ['month', ONE_DAY * 62], // 2M ['week', ONE_DAY * 42], // 10w ['quarter', ONE_DAY * 380 / 4], // 3M ['month', ONE_DAY * 31 * 4], // 4M ['month', ONE_DAY * 31 * 5], // 5M ['half-year', ONE_DAY * 380 / 2], // 6M ['month', ONE_DAY * 31 * 8], // 8M ['month', ONE_DAY * 31 * 10], // 10M ['year', ONE_DAY * 380] // 1Y ]; /** * @param {module:echarts/model/Model} * @return {module:echarts/scale/Time} */ TimeScale.create = function (model) { return new TimeScale({useUTC: model.ecModel.get('useUTC')}); }; /** * Log scale * @module echarts/scale/Log */ // Use some method of IntervalScale var scaleProto$1 = Scale.prototype; var intervalScaleProto$1 = IntervalScale.prototype; var getPrecisionSafe$1 = getPrecisionSafe; var roundingErrorFix = round$1; var mathFloor$1 = Math.floor; var mathCeil$1 = Math.ceil; var mathPow$1 = Math.pow; var mathLog = Math.log; var LogScale = Scale.extend({ type: 'log', base: 10, $constructor: function () { Scale.apply(this, arguments); this._originalScale = new IntervalScale(); }, /** * @return {Array.<number>} */ getTicks: function () { var originalScale = this._originalScale; var extent = this._extent; var originalExtent = originalScale.getExtent(); return map(intervalScaleProto$1.getTicks.call(this), function (val) { var powVal = round$1(mathPow$1(this.base, val)); // Fix #4158 powVal = (val === extent[0] && originalScale.__fixMin) ? fixRoundingError(powVal, originalExtent[0]) : powVal; powVal = (val === extent[1] && originalScale.__fixMax) ? fixRoundingError(powVal, originalExtent[1]) : powVal; return powVal; }, this); }, /** * @param {number} val * @return {string} */ getLabel: intervalScaleProto$1.getLabel, /** * @param {number} val * @return {number} */ scale: function (val) { val = scaleProto$1.scale.call(this, val); return mathPow$1(this.base, val); }, /** * @param {number} start * @param {number} end */ setExtent: function (start, end) { var base = this.base; start = mathLog(start) / mathLog(base); end = mathLog(end) / mathLog(base); intervalScaleProto$1.setExtent.call(this, start, end); }, /** * @return {number} end */ getExtent: function () { var base = this.base; var extent = scaleProto$1.getExtent.call(this); extent[0] = mathPow$1(base, extent[0]); extent[1] = mathPow$1(base, extent[1]); // Fix #4158 var originalScale = this._originalScale; var originalExtent = originalScale.getExtent(); originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0])); originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1])); return extent; }, /** * @param {Array.<number>} extent */ unionExtent: function (extent) { this._originalScale.unionExtent(extent); var base = this.base; extent[0] = mathLog(extent[0]) / mathLog(base); extent[1] = mathLog(extent[1]) / mathLog(base); scaleProto$1.unionExtent.call(this, extent); }, /** * @override */ unionExtentFromData: function (data, dim) { // TODO // filter value that <= 0 this.unionExtent(data.getApproximateExtent(dim)); }, /** * Update interval and extent of intervals for nice ticks * @param {number} [approxTickNum = 10] Given approx tick number */ niceTicks: function (approxTickNum) { approxTickNum = approxTickNum || 10; var extent = this._extent; var span = extent[1] - extent[0]; if (span === Infinity || span <= 0) { return; } var interval = quantity(span); var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count. if (err <= 0.5) { interval *= 10; } // Interval should be integer while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) { interval *= 10; } var niceExtent = [ round$1(mathCeil$1(extent[0] / interval) * interval), round$1(mathFloor$1(extent[1] / interval) * interval) ]; this._interval = interval; this._niceExtent = niceExtent; }, /** * Nice extent. * @override */ niceExtent: function (opt) { intervalScaleProto$1.niceExtent.call(this, opt); var originalScale = this._originalScale; originalScale.__fixMin = opt.fixMin; originalScale.__fixMax = opt.fixMax; } }); each$1(['contain', 'normalize'], function (methodName) { LogScale.prototype[methodName] = function (val) { val = mathLog(val) / mathLog(this.base); return scaleProto$1[methodName].call(this, val); }; }); LogScale.create = function () { return new LogScale(); }; function fixRoundingError(val, originalVal) { return roundingErrorFix(val, getPrecisionSafe$1(originalVal)); } /** * Get axis scale extent before niced. * Item of returned array can only be number (including Infinity and NaN). */ function getScaleExtent(scale, model) { var scaleType = scale.type; var min = model.getMin(); var max = model.getMax(); var fixMin = min != null; var fixMax = max != null; var originalExtent = scale.getExtent(); var axisDataLen; var boundaryGap; var span; if (scaleType === 'ordinal') { axisDataLen = model.getCategories().length; } else { boundaryGap = model.get('boundaryGap'); if (!isArray(boundaryGap)) { boundaryGap = [boundaryGap || 0, boundaryGap || 0]; } if (typeof boundaryGap[0] === 'boolean') { if (__DEV__) { console.warn('Boolean type for boundaryGap is only ' + 'allowed for ordinal axis. Please use string in ' + 'percentage instead, e.g., "20%". Currently, ' + 'boundaryGap is set to be 0.'); } boundaryGap = [0, 0]; } boundaryGap[0] = parsePercent$1(boundaryGap[0], 1); boundaryGap[1] = parsePercent$1(boundaryGap[1], 1); span = (originalExtent[1] - originalExtent[0]) || Math.abs(originalExtent[0]); } // Notice: When min/max is not set (that is, when there are null/undefined, // which is the most common case), these cases should be ensured: // (1) For 'ordinal', show all axis.data. // (2) For others: // + `boundaryGap` is applied (if min/max set, boundaryGap is // disabled). // + If `needCrossZero`, min/max should be zero, otherwise, min/max should // be the result that originalExtent enlarged by boundaryGap. // (3) If no data, it should be ensured that `scale.setBlank` is set. // FIXME // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used? // (2) When `needCrossZero` and all data is positive/negative, should it be ensured // that the results processed by boundaryGap are positive/negative? if (min == null) { min = scaleType === 'ordinal' ? (axisDataLen ? 0 : NaN) : originalExtent[0] - boundaryGap[0] * span; } if (max == null) { max = scaleType === 'ordinal' ? (axisDataLen ? axisDataLen - 1 : NaN) : originalExtent[1] + boundaryGap[1] * span; } if (min === 'dataMin') { min = originalExtent[0]; } else if (typeof min === 'function') { min = min({ min: originalExtent[0], max: originalExtent[1] }); } if (max === 'dataMax') { max = originalExtent[1]; } else if (typeof max === 'function') { max = max({ min: originalExtent[0], max: originalExtent[1] }); } (min == null || !isFinite(min)) && (min = NaN); (max == null || !isFinite(max)) && (max = NaN); scale.setBlank(eqNaN(min) || eqNaN(max)); // Evaluate if axis needs cross zero if (model.getNeedCrossZero()) { // Axis is over zero and min is not set if (min > 0 && max > 0 && !fixMin) { min = 0; } // Axis is under zero and max is not set if (min < 0 && max < 0 && !fixMax) { max = 0; } } // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis // is base axis // FIXME // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly. // (2) Refactor the logic with `barGrid`. Is it not need to `calBarWidthAndOffset` twice with different extent? // Should not depend on series type `bar`? // (3) Fix that might overlap when using dataZoom. // (4) Consider other chart types using `barGrid`? // See #6728, #4862, `test/bar-overflow-time-plot.html` var ecModel = model.ecModel; if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) { var barSeriesModels = []; var isBaseAxisAndHasBarSeries; ecModel.eachSeriesByType('bar', function (seriesModel) { if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') { barSeriesModels.push(seriesModel); isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis; } }); if (isBaseAxisAndHasBarSeries) { // Adjust axis min and max to account for overflow var adjustedScale = adjustScaleForOverflow(min, max, model, barSeriesModels); min = adjustedScale.min; max = adjustedScale.max; } } return [min, max]; } function adjustScaleForOverflow(min, max, model, barSeriesModels) { // Get Axis Length var axisExtent = model.axis.getExtent(); var axisLength = axisExtent[1] - axisExtent[0]; // Calculate placement of bars on axis var barWidthAndOffset = calBarWidthAndOffset(barSeriesModels); // Get bars on current base axis and calculate min and max overflow var baseAxisKey = model.axis.dim + model.axis.index; var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey]; if (barsOnCurrentAxis === undefined) { return {min: min, max: max}; } var minOverflow = Infinity; each$1(barsOnCurrentAxis, function (item) { minOverflow = Math.min(item.offset, minOverflow); }); var maxOverflow = -Infinity; each$1(barsOnCurrentAxis, function (item) { maxOverflow = Math.max(item.offset + item.width, maxOverflow); }); minOverflow = Math.abs(minOverflow); maxOverflow = Math.abs(maxOverflow); var totalOverFlow = minOverflow + maxOverflow; // Calulate required buffer based on old range and overflow var oldRange = max - min; var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength); var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange); max += overflowBuffer * (maxOverflow / totalOverFlow); min -= overflowBuffer * (minOverflow / totalOverFlow); return {min: min, max: max}; } function niceScaleExtent$1(scale, model) { var extent = getScaleExtent(scale, model); var fixMin = model.getMin() != null; var fixMax = model.getMax() != null; var splitNumber = model.get('splitNumber'); if (scale.type === 'log') { scale.base = model.get('logBase'); } var scaleType = scale.type; scale.setExtent(extent[0], extent[1]); scale.niceExtent({ splitNumber: splitNumber, fixMin: fixMin, fixMax: fixMax, minInterval: (scaleType === 'interval' || scaleType === 'time') ? model.get('minInterval') : null, maxInterval: (scaleType === 'interval' || scaleType === 'time') ? model.get('maxInterval') : null }); // If some one specified the min, max. And the default calculated interval // is not good enough. He can specify the interval. It is often appeared // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard // to be 60. // FIXME var interval = model.get('interval'); if (interval != null) { scale.setInterval && scale.setInterval(interval); } } /** * @param {module:echarts/model/Model} model * @param {string} [axisType] Default retrieve from model.type * @return {module:echarts/scale/*} */ function createScaleByModel(model, axisType) { axisType = axisType || model.get('type'); if (axisType) { switch (axisType) { // Buildin scale case 'category': return new OrdinalScale( model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(), [Infinity, -Infinity] ); case 'value': return new IntervalScale(); // Extended scale, like time and log default: return (Scale.getClass(axisType) || IntervalScale).create(model); } } } /** * Check if the axis corss 0 */ function ifAxisCrossZero$1(axis) { var dataExtent = axis.scale.getExtent(); var min = dataExtent[0]; var max = dataExtent[1]; return !((min > 0 && max > 0) || (min < 0 && max < 0)); } /** * @param {Array.<number>} tickCoords In axis self coordinate. * @param {Array.<string>} labels * @param {string} font * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative. * @return {number} */ function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) { var textSpaceTakenRect; var autoLabelInterval = 0; var accumulatedLabelInterval = 0; var rotation = (axisRotate - labelRotate) / 180 * Math.PI; var step = 1; if (labels.length > 40) { // Simple optimization for large amount of labels step = Math.floor(labels.length / 40); } for (var i = 0; i < tickCoords.length; i += step) { var tickCoord = tickCoords[i]; // Not precise, do not consider align and vertical align // and each distance from axis line yet. var rect = getBoundingRect( labels[i], font, 'center', 'top' ); rect.x += tickCoord * Math.cos(rotation); rect.y += tickCoord * Math.sin(rotation); // Magic number rect.width *= 1.3; rect.height *= 1.3; if (!textSpaceTakenRect) { textSpaceTakenRect = rect.clone(); } // There is no space for current label; else if (textSpaceTakenRect.intersect(rect)) { accumulatedLabelInterval++; autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval); } else { textSpaceTakenRect.union(rect); // Reset accumulatedLabelInterval = 0; } } if (autoLabelInterval === 0 && step > 1) { return step; } return (autoLabelInterval + 1) * step - 1; } /** * @param {Object} axis * @param {Function} labelFormatter * @return {Array.<string>} */ function getFormattedLabels(axis, labelFormatter) { var scale = axis.scale; var labels = scale.getTicksLabels(); var ticks = scale.getTicks(); if (typeof labelFormatter === 'string') { labelFormatter = (function (tpl) { return function (val) { return tpl.replace('{value}', val != null ? val : ''); }; })(labelFormatter); // Consider empty array return map(labels, labelFormatter); } else if (typeof labelFormatter === 'function') { return map(ticks, function (tick, idx) { return labelFormatter( getAxisRawValue(axis, tick), idx ); }, this); } else { return labels; } } function getAxisRawValue(axis, value) { // In category axis with data zoom, tick is not the original // index of axis.data. So tick should not be exposed to user // in category axis. return axis.type === 'category' ? axis.scale.getLabel(value) : value; } /** * Cartesian coordinate system * @module echarts/coord/Cartesian * */ function dimAxisMapper(dim) { return this._axes[dim]; } /** * @alias module:echarts/coord/Cartesian * @constructor */ var Cartesian = function (name) { this._axes = {}; this._dimList = []; /** * @type {string} */ this.name = name || ''; }; Cartesian.prototype = { constructor: Cartesian, type: 'cartesian', /** * Get axis * @param {number|string} dim * @return {module:echarts/coord/Cartesian~Axis} */ getAxis: function (dim) { return this._axes[dim]; }, /** * Get axes list * @return {Array.<module:echarts/coord/Cartesian~Axis>} */ getAxes: function () { return map(this._dimList, dimAxisMapper, this); }, /** * Get axes list by given scale type */ getAxesByScale: function (scaleType) { scaleType = scaleType.toLowerCase(); return filter( this.getAxes(), function (axis) { return axis.scale.type === scaleType; } ); }, /** * Add axis * @param {module:echarts/coord/Cartesian.Axis} */ addAxis: function (axis) { var dim = axis.dim; this._axes[dim] = axis; this._dimList.push(dim); }, /** * Convert data to coord in nd space * @param {Array.<number>|Object.<string, number>} val * @return {Array.<number>|Object.<string, number>} */ dataToCoord: function (val) { return this._dataCoordConvert(val, 'dataToCoord'); }, /** * Convert coord in nd space to data * @param {Array.<number>|Object.<string, number>} val * @return {Array.<number>|Object.<string, number>} */ coordToData: function (val) { return this._dataCoordConvert(val, 'coordToData'); }, _dataCoordConvert: function (input, method) { var dimList = this._dimList; var output = input instanceof Array ? [] : {}; for (var i = 0; i < dimList.length; i++) { var dim = dimList[i]; var axis = this._axes[dim]; output[dim] = axis[method](input[dim]); } return output; } }; function Cartesian2D(name) { Cartesian.call(this, name); } Cartesian2D.prototype = { constructor: Cartesian2D, type: 'cartesian2d', /** * @type {Array.<string>} * @readOnly */ dimensions: ['x', 'y'], /** * Base axis will be used on stacking. * * @return {module:echarts/coord/cartesian/Axis2D} */ getBaseAxis: function () { return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x'); }, /** * If contain point * @param {Array.<number>} point * @return {boolean} */ containPoint: function (point) { var axisX = this.getAxis('x'); var axisY = this.getAxis('y'); return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1])); }, /** * If contain data * @param {Array.<number>} data * @return {boolean} */ containData: function (data) { return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]); }, /** * @param {Array.<number>} data * @param {Array.<number>} out * @return {Array.<number>} */ dataToPoint: function (data, reserved, out) { var xAxis = this.getAxis('x'); var yAxis = this.getAxis('y'); out = out || []; out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0])); out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1])); return out; }, /** * @param {Array.<number>} data * @param {Array.<number>} out * @return {Array.<number>} */ clampData: function (data, out) { var xAxisExtent = this.getAxis('x').scale.getExtent(); var yAxisExtent = this.getAxis('y').scale.getExtent(); out = out || []; out[0] = Math.min( Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]), Math.max(xAxisExtent[0], xAxisExtent[1]) ); out[1] = Math.min( Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]), Math.max(yAxisExtent[0], yAxisExtent[1]) ); return out; }, /** * @param {Array.<number>} point * @param {Array.<number>} out * @return {Array.<number>} */ pointToData: function (point, out) { var xAxis = this.getAxis('x'); var yAxis = this.getAxis('y'); out = out || []; out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0])); out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1])); return out; }, /** * Get other axis * @param {module:echarts/coord/cartesian/Axis2D} axis */ getOtherAxis: function (axis) { return this.getAxis(axis.dim === 'x' ? 'y' : 'x'); } }; inherits(Cartesian2D, Cartesian); var linearMap$1 = linearMap; function fixExtentWithBands(extent, nTick) { var size = extent[1] - extent[0]; var len = nTick; var margin = size / len / 2; extent[0] += margin; extent[1] -= margin; } var normalizedExtent = [0, 1]; /** * @name module:echarts/coord/CartesianAxis * @constructor */ var Axis = function (dim, scale, extent) { /** * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius' * @type {string} */ this.dim = dim; /** * Axis scale * @type {module:echarts/coord/scale/*} */ this.scale = scale; /** * @type {Array.<number>} * @private */ this._extent = extent || [0, 0]; /** * @type {boolean} */ this.inverse = false; /** * Usually true when axis has a ordinal scale * @type {boolean} */ this.onBand = false; /** * @private * @type {number} */ this._labelInterval; }; Axis.prototype = { constructor: Axis, /** * If axis extent contain given coord * @param {number} coord * @return {boolean} */ contain: function (coord) { var extent = this._extent; var min = Math.min(extent[0], extent[1]); var max = Math.max(extent[0], extent[1]); return coord >= min && coord <= max; }, /** * If axis extent contain given data * @param {number} data * @return {boolean} */ containData: function (data) { return this.contain(this.dataToCoord(data)); }, /** * Get coord extent. * @return {Array.<number>} */ getExtent: function () { return this._extent.slice(); }, /** * Get precision used for formatting * @param {Array.<number>} [dataExtent] * @return {number} */ getPixelPrecision: function (dataExtent) { return getPixelPrecision( dataExtent || this.scale.getExtent(), this._extent ); }, /** * Set coord extent * @param {number} start * @param {number} end */ setExtent: function (start, end) { var extent = this._extent; extent[0] = start; extent[1] = end; }, /** * Convert data to coord. Data is the rank if it has an ordinal scale * @param {number} data * @param {boolean} clamp * @return {number} */ dataToCoord: function (data, clamp) { var extent = this._extent; var scale = this.scale; data = scale.normalize(data); if (this.onBand && scale.type === 'ordinal') { extent = extent.slice(); fixExtentWithBands(extent, scale.count()); } return linearMap$1(data, normalizedExtent, extent, clamp); }, /** * Convert coord to data. Data is the rank if it has an ordinal scale * @param {number} coord * @param {boolean} clamp * @return {number} */ coordToData: function (coord, clamp) { var extent = this._extent; var scale = this.scale; if (this.onBand && scale.type === 'ordinal') { extent = extent.slice(); fixExtentWithBands(extent, scale.count()); } var t = linearMap$1(coord, extent, normalizedExtent, clamp); return this.scale.scale(t); }, /** * Convert pixel point to data in axis * @param {Array.<number>} point * @param {boolean} clamp * @return {number} data */ pointToData: function (point, clamp) { // Should be implemented in derived class if necessary. }, /** * @return {Array.<number>} */ getTicksCoords: function (alignWithLabel) { if (this.onBand && !alignWithLabel) { var bands = this.getBands(); var coords = []; for (var i = 0; i < bands.length; i++) { coords.push(bands[i][0]); } if (bands[i - 1]) { coords.push(bands[i - 1][1]); } return coords; } else { return map(this.scale.getTicks(), this.dataToCoord, this); } }, /** * Coords of labels are on the ticks or on the middle of bands * @return {Array.<number>} */ getLabelsCoords: function () { return map(this.scale.getTicks(), this.dataToCoord, this); }, /** * Get bands. * * If axis has labels [1, 2, 3, 4]. Bands on the axis are * |---1---|---2---|---3---|---4---|. * * @return {Array} */ // FIXME Situation when labels is on ticks getBands: function () { var extent = this.getExtent(); var bands = []; var len = this.scale.count(); var start = extent[0]; var end = extent[1]; var span = end - start; for (var i = 0; i < len; i++) { bands.push([ span * i / len + start, span * (i + 1) / len + start ]); } return bands; }, /** * Get width of band * @return {number} */ getBandWidth: function () { var axisExtent = this._extent; var dataExtent = this.scale.getExtent(); var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data. len === 0 && (len = 1); var size = Math.abs(axisExtent[1] - axisExtent[0]); return Math.abs(size) / len; }, /** * @abstract * @return {boolean} Is horizontal */ isHorizontal: null, /** * @abstract * @return {number} Get axis rotate, by degree. */ getRotate: null, /** * Get interval of the axis label. * To get precise result, at least one of `getRotate` and `isHorizontal` * should be implemented. * @return {number} */ getLabelInterval: function () { var labelInterval = this._labelInterval; if (!labelInterval) { var axisModel = this.model; var labelModel = axisModel.getModel('axisLabel'); labelInterval = labelModel.get('interval'); if (this.type === 'category' && (labelInterval == null || labelInterval === 'auto') ) { labelInterval = getAxisLabelInterval( map(this.scale.getTicks(), this.dataToCoord, this), axisModel.getFormattedLabels(), labelModel.getFont(), this.getRotate ? this.getRotate() : (this.isHorizontal && !this.isHorizontal()) ? 90 : 0, labelModel.get('rotate') ); } this._labelInterval = labelInterval; } return labelInterval; } }; /** * Extend axis 2d * @constructor module:echarts/coord/cartesian/Axis2D * @extends {module:echarts/coord/cartesian/Axis} * @param {string} dim * @param {*} scale * @param {Array.<number>} coordExtent * @param {string} axisType * @param {string} position */ var Axis2D = function (dim, scale, coordExtent, axisType, position) { Axis.call(this, dim, scale, coordExtent); /** * Axis type * - 'category' * - 'value' * - 'time' * - 'log' * @type {string} */ this.type = axisType || 'value'; /** * Axis position * - 'top' * - 'bottom' * - 'left' * - 'right' */ this.position = position || 'bottom'; }; Axis2D.prototype = { constructor: Axis2D, /** * Index of axis, can be used as key */ index: 0, /** * If axis is on the zero position of the other axis * @type {boolean} */ onZero: false, /** * Axis model * @param {module:echarts/coord/cartesian/AxisModel} */ model: null, isHorizontal: function () { var position = this.position; return position === 'top' || position === 'bottom'; }, /** * Each item cooresponds to this.getExtent(), which * means globalExtent[0] may greater than globalExtent[1], * unless `asc` is input. * * @param {boolean} [asc] * @return {Array.<number>} */ getGlobalExtent: function (asc) { var ret = this.getExtent(); ret[0] = this.toGlobalCoord(ret[0]); ret[1] = this.toGlobalCoord(ret[1]); asc && ret[0] > ret[1] && ret.reverse(); return ret; }, getOtherAxis: function () { this.grid.getOtherAxis(); }, /** * If label is ignored. * Automatically used when axis is category and label can not be all shown * @param {number} idx * @return {boolean} */ isLabelIgnored: function (idx) { if (this.type === 'category') { var labelInterval = this.getLabelInterval(); return ((typeof labelInterval === 'function') && !labelInterval(idx, this.scale.getLabel(idx))) || idx % (labelInterval + 1); } }, /** * @override */ pointToData: function (point, clamp) { return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp); }, /** * Transform global coord to local coord, * i.e. var localCoord = axis.toLocalCoord(80); * designate by module:echarts/coord/cartesian/Grid. * @type {Function} */ toLocalCoord: null, /** * Transform global coord to local coord, * i.e. var globalCoord = axis.toLocalCoord(40); * designate by module:echarts/coord/cartesian/Grid. * @type {Function} */ toGlobalCoord: null }; inherits(Axis2D, Axis); var defaultOption = { show: true, zlevel: 0, // 一级层叠 z: 0, // 二级层叠 // 反向坐标轴 inverse: false, // 坐标轴名字,默认为空 name: '', // 坐标轴名字位置,支持'start' | 'middle' | 'end' nameLocation: 'end', // 坐标轴名字旋转,degree。 nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'. nameTruncate: { maxWidth: null, ellipsis: '...', placeholder: '.' }, // 坐标轴文字样式,默认取全局样式 nameTextStyle: {}, // 文字与轴线距离 nameGap: 15, silent: false, // Default false to support tooltip. triggerEvent: false, // Default false to avoid legacy user event listener fail. tooltip: { show: false }, axisPointer: {}, // 坐标轴线 axisLine: { // 默认显示,属性show控制显示与否 show: true, onZero: true, onZeroAxisIndex: null, // 属性lineStyle控制线条样式 lineStyle: { color: '#333', width: 1, type: 'solid' }, // 坐标轴两端的箭头 symbol: ['none', 'none'], symbolSize: [10, 15] }, // 坐标轴小标记 axisTick: { // 属性show控制显示与否,默认显示 show: true, // 控制小标记是否在grid里 inside: false, // 属性length控制线长 length: 5, // 属性lineStyle控制线条样式 lineStyle: { width: 1 } }, // 坐标轴文本标签,详见axis.axisLabel axisLabel: { show: true, // 控制文本标签是否在grid里 inside: false, rotate: 0, showMinLabel: null, // true | false | null (auto) showMaxLabel: null, // true | false | null (auto) margin: 8, // formatter: null, // 其余属性默认使用全局文本样式,详见TEXTSTYLE fontSize: 12 }, // 分隔线 splitLine: { // 默认显示,属性show控制显示与否 show: true, // 属性lineStyle(详见lineStyle)控制线条样式 lineStyle: { color: ['#ccc'], width: 1, type: 'solid' } }, // 分隔区域 splitArea: { // 默认不显示,属性show控制显示与否 show: false, // 属性areaStyle(详见areaStyle)控制区域样式 areaStyle: { color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)'] } } }; var axisDefault = {}; axisDefault.categoryAxis = merge({ // 类目起始和结束两端空白策略 boundaryGap: true, // Set false to faster category collection. // Only usefull in the case like: category is // ['2012-01-01', '2012-01-02', ...], where the input // data has been ensured not duplicate and is large data. // null means "auto": // if axis.data provided, do not deduplication, // else do deduplication. deduplication: null, // splitArea: { // show: false // }, splitLine: { show: false }, // 坐标轴小标记 axisTick: { // If tick is align with label when boundaryGap is true alignWithLabel: false, interval: 'auto' }, // 坐标轴文本标签,详见axis.axisLabel axisLabel: { interval: 'auto' } }, defaultOption); axisDefault.valueAxis = merge({ // 数值起始和结束两端空白策略 boundaryGap: [0, 0], // TODO // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60] // 最小值, 设置成 'dataMin' 则从数据中计算最小值 // min: null, // 最大值,设置成 'dataMax' 则从数据中计算最大值 // max: null, // Readonly prop, specifies start value of the range when using data zoom. // rangeStart: null // Readonly prop, specifies end value of the range when using data zoom. // rangeEnd: null // 脱离0值比例,放大聚焦到最终_min,_max区间 // scale: false, // 分割段数,默认为5 splitNumber: 5 // Minimum interval // minInterval: null // maxInterval: null }, defaultOption); // FIXME axisDefault.timeAxis = defaults({ scale: true, min: 'dataMin', max: 'dataMax' }, axisDefault.valueAxis); axisDefault.logAxis = defaults({ scale: true, logBase: 10 }, axisDefault.valueAxis); // FIXME axisType is fixed ? var AXIS_TYPES = ['value', 'category', 'time', 'log']; /** * Generate sub axis model class * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel' * @param {module:echarts/model/Component} BaseAxisModelClass * @param {Function} axisTypeDefaulter * @param {Object} [extraDefaultOption] */ var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) { each$1(AXIS_TYPES, function (axisType) { BaseAxisModelClass.extend({ /** * @readOnly */ type: axisName + 'Axis.' + axisType, mergeDefaultAndTheme: function (option, ecModel) { var layoutMode = this.layoutMode; var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; var themeModel = ecModel.getTheme(); merge(option, themeModel.get(axisType + 'Axis')); merge(option, this.getDefaultOption()); option.type = axisTypeDefaulter(axisName, option); if (layoutMode) { mergeLayoutParam(option, inputPositionParams, layoutMode); } }, /** * @override */ optionUpdated: function () { var thisOption = this.option; if (thisOption.type === 'category') { this.__ordinalMeta = OrdinalMeta.createByAxisModel(this); } }, /** * Should not be called before all of 'getInitailData' finished. * Because categories are collected during initializing data. */ getCategories: function () { // FIXME // warning if called before all of 'getInitailData' finished. if (this.option.type === 'category') { return this.__ordinalMeta.categories; } }, getOrdinalMeta: function () { return this.__ordinalMeta; }, defaultOption: mergeAll( [ {}, axisDefault[axisType + 'Axis'], extraDefaultOption ], true ) }); }); ComponentModel.registerSubTypeDefaulter( axisName + 'Axis', curry(axisTypeDefaulter, axisName) ); }; var axisModelCommonMixin = { /** * Format labels * @return {Array.<string>} */ getFormattedLabels: function () { return getFormattedLabels( this.axis, this.get('axisLabel.formatter') ); }, /** * @param {boolean} origin * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN */ getMin: function (origin) { var option = this.option; var min = (!origin && option.rangeStart != null) ? option.rangeStart : option.min; if (this.axis && min != null && min !== 'dataMin' && typeof min !== 'function' && !eqNaN(min) ) { min = this.axis.scale.parse(min); } return min; }, /** * @param {boolean} origin * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN */ getMax: function (origin) { var option = this.option; var max = (!origin && option.rangeEnd != null) ? option.rangeEnd : option.max; if (this.axis && max != null && max !== 'dataMax' && typeof max !== 'function' && !eqNaN(max) ) { max = this.axis.scale.parse(max); } return max; }, /** * @return {boolean} */ getNeedCrossZero: function () { var option = this.option; return (option.rangeStart != null || option.rangeEnd != null) ? false : !option.scale; }, /** * Should be implemented by each axis model if necessary. * @return {module:echarts/model/Component} coordinate system model */ getCoordSysModel: noop, /** * @param {number} rangeStart Can only be finite number or null/undefined or NaN. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN. */ setRange: function (rangeStart, rangeEnd) { this.option.rangeStart = rangeStart; this.option.rangeEnd = rangeEnd; }, /** * Reset range */ resetRange: function () { // rangeStart and rangeEnd is readonly. this.option.rangeStart = this.option.rangeEnd = null; } }; var AxisModel = ComponentModel.extend({ type: 'cartesian2dAxis', /** * @type {module:echarts/coord/cartesian/Axis2D} */ axis: null, /** * @override */ init: function () { AxisModel.superApply(this, 'init', arguments); this.resetRange(); }, /** * @override */ mergeOption: function () { AxisModel.superApply(this, 'mergeOption', arguments); this.resetRange(); }, /** * @override */ restoreData: function () { AxisModel.superApply(this, 'restoreData', arguments); this.resetRange(); }, /** * @override * @return {module:echarts/model/Component} */ getCoordSysModel: function () { return this.ecModel.queryComponents({ mainType: 'grid', index: this.option.gridIndex, id: this.option.gridId })[0]; } }); function getAxisType(axisDim, option) { // Default axis with data is category axis return option.type || (option.data ? 'category' : 'value'); } merge(AxisModel.prototype, axisModelCommonMixin); var extraOption = { // gridIndex: 0, // gridId: '', // Offset is for multiple axis on the same position offset: 0 }; axisModelCreator('x', AxisModel, getAxisType, extraOption); axisModelCreator('y', AxisModel, getAxisType, extraOption); // Grid 是在有直角坐标系的时候必须要存在的 // 所以这里也要被 Cartesian2D 依赖 ComponentModel.extend({ type: 'grid', dependencies: ['xAxis', 'yAxis'], layoutMode: 'box', /** * @type {module:echarts/coord/cartesian/Grid} */ coordinateSystem: null, defaultOption: { show: false, zlevel: 0, z: 0, left: '10%', top: 60, right: '10%', bottom: 60, // If grid size contain label containLabel: false, // width: {totalWidth} - left - right, // height: {totalHeight} - top - bottom, backgroundColor: 'rgba(0,0,0,0)', borderWidth: 1, borderColor: '#ccc' } }); /** * Grid is a region which contains at most 4 cartesian systems * * TODO Default cartesian */ // Depends on GridModel, AxisModel, which performs preprocess. var each$6 = each$1; var ifAxisCrossZero = ifAxisCrossZero$1; var niceScaleExtent = niceScaleExtent$1; /** * Check if the axis is used in the specified grid * @inner */ function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) { return axisModel.getCoordSysModel() === gridModel; } function rotateTextRect(textRect, rotate) { var rotateRadians = rotate * Math.PI / 180; var boundingBox = textRect.plain(); var beforeWidth = boundingBox.width; var beforeHeight = boundingBox.height; var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians); var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians); var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight); return rotatedRect; } function getLabelUnionRect(axis) { var axisModel = axis.model; var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : []; var axisLabelModel = axisModel.getModel('axisLabel'); var rect; var step = 1; var labelCount = labels.length; if (labelCount > 40) { // Simple optimization for large amount of labels step = Math.ceil(labelCount / 40); } for (var i = 0; i < labelCount; i += step) { if (!axis.isLabelIgnored(i)) { var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]); var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0); rect ? rect.union(singleRect) : (rect = singleRect); } } return rect; } function Grid(gridModel, ecModel, api) { /** * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>} * @private */ this._coordsMap = {}; /** * @type {Array.<module:echarts/coord/cartesian/Cartesian>} * @private */ this._coordsList = []; /** * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>} * @private */ this._axesMap = {}; /** * @type {Array.<module:echarts/coord/cartesian/Axis2D>} * @private */ this._axesList = []; this._initCartesian(gridModel, ecModel, api); this.model = gridModel; } var gridProto = Grid.prototype; gridProto.type = 'grid'; gridProto.axisPointerEnabled = true; gridProto.getRect = function () { return this._rect; }; gridProto.update = function (ecModel, api) { var axesMap = this._axesMap; this._updateScale(ecModel, this.model); each$6(axesMap.x, function (xAxis) { niceScaleExtent(xAxis.scale, xAxis.model); }); each$6(axesMap.y, function (yAxis) { niceScaleExtent(yAxis.scale, yAxis.model); }); each$6(axesMap.x, function (xAxis) { fixAxisOnZero(axesMap, 'y', xAxis); }); each$6(axesMap.y, function (yAxis) { fixAxisOnZero(axesMap, 'x', yAxis); }); // Resize again if containLabel is enabled // FIXME It may cause getting wrong grid size in data processing stage this.resize(this.model, api); }; function fixAxisOnZero(axesMap, otherAxisDim, axis) { // onZero can not be enabled in these two situations: // 1. When any other axis is a category axis. // 2. When no axis is cross 0 point. var axes = axesMap[otherAxisDim]; if (!axis.onZero) { return; } var onZeroAxisIndex = axis.onZeroAxisIndex; // If target axis is specified. if (onZeroAxisIndex != null) { var otherAxis = axes[onZeroAxisIndex]; if (otherAxis && canNotOnZeroToAxis(otherAxis)) { axis.onZero = false; } return; } for (var idx in axes) { if (axes.hasOwnProperty(idx)) { var otherAxis = axes[idx]; if (otherAxis && !canNotOnZeroToAxis(otherAxis)) { onZeroAxisIndex = +idx; break; } } } if (onZeroAxisIndex == null) { axis.onZero = false; } axis.onZeroAxisIndex = onZeroAxisIndex; } function canNotOnZeroToAxis(axis) { return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero(axis); } /** * Resize the grid * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {module:echarts/ExtensionAPI} api */ gridProto.resize = function (gridModel, api, ignoreContainLabel) { var gridRect = getLayoutRect( gridModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }); this._rect = gridRect; var axesList = this._axesList; adjustAxes(); // Minus label size if (!ignoreContainLabel && gridModel.get('containLabel')) { each$6(axesList, function (axis) { if (!axis.model.get('axisLabel.inside')) { var labelUnionRect = getLabelUnionRect(axis); if (labelUnionRect) { var dim = axis.isHorizontal() ? 'height' : 'width'; var margin = axis.model.get('axisLabel.margin'); gridRect[dim] -= labelUnionRect[dim] + margin; if (axis.position === 'top') { gridRect.y += labelUnionRect.height + margin; } else if (axis.position === 'left') { gridRect.x += labelUnionRect.width + margin; } } } }); adjustAxes(); } function adjustAxes() { each$6(axesList, function (axis) { var isHorizontal = axis.isHorizontal(); var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height]; var idx = axis.inverse ? 1 : 0; axis.setExtent(extent[idx], extent[1 - idx]); updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y); }); } }; /** * @param {string} axisType * @param {number} [axisIndex] */ gridProto.getAxis = function (axisType, axisIndex) { var axesMapOnDim = this._axesMap[axisType]; if (axesMapOnDim != null) { if (axisIndex == null) { // Find first axis for (var name in axesMapOnDim) { if (axesMapOnDim.hasOwnProperty(name)) { return axesMapOnDim[name]; } } } return axesMapOnDim[axisIndex]; } }; /** * @return {Array.<module:echarts/coord/Axis>} */ gridProto.getAxes = function () { return this._axesList.slice(); }; /** * Usage: * grid.getCartesian(xAxisIndex, yAxisIndex); * grid.getCartesian(xAxisIndex); * grid.getCartesian(null, yAxisIndex); * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...}); * * @param {number|Object} [xAxisIndex] * @param {number} [yAxisIndex] */ gridProto.getCartesian = function (xAxisIndex, yAxisIndex) { if (xAxisIndex != null && yAxisIndex != null) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex; return this._coordsMap[key]; } if (isObject$1(xAxisIndex)) { yAxisIndex = xAxisIndex.yAxisIndex; xAxisIndex = xAxisIndex.xAxisIndex; } // When only xAxisIndex or yAxisIndex given, find its first cartesian. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) { if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex ) { return coordList[i]; } } }; gridProto.getCartesians = function () { return this._coordsList.slice(); }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.convertToPixel = function (ecModel, finder, value) { var target = this._findConvertTarget(ecModel, finder); return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null; }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.convertFromPixel = function (ecModel, finder, value) { var target = this._findConvertTarget(ecModel, finder); return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null; }; /** * @inner */ gridProto._findConvertTarget = function (ecModel, finder) { var seriesModel = finder.seriesModel; var xAxisModel = finder.xAxisModel || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]); var yAxisModel = finder.yAxisModel || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]); var gridModel = finder.gridModel; var coordsList = this._coordsList; var cartesian; var axis; if (seriesModel) { cartesian = seriesModel.coordinateSystem; indexOf(coordsList, cartesian) < 0 && (cartesian = null); } else if (xAxisModel && yAxisModel) { cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex); } else if (xAxisModel) { axis = this.getAxis('x', xAxisModel.componentIndex); } else if (yAxisModel) { axis = this.getAxis('y', yAxisModel.componentIndex); } // Lowest priority. else if (gridModel) { var grid = gridModel.coordinateSystem; if (grid === this) { cartesian = this._coordsList[0]; } } return {cartesian: cartesian, axis: axis}; }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.containPoint = function (point) { var coord = this._coordsList[0]; if (coord) { return coord.containPoint(point); } }; /** * Initialize cartesian coordinate systems * @private */ gridProto._initCartesian = function (gridModel, ecModel, api) { var axisPositionUsed = { left: false, right: false, top: false, bottom: false }; var axesMap = { x: {}, y: {} }; var axesCount = { x: 0, y: 0 }; /// Create axis ecModel.eachComponent('xAxis', createAxisCreator('x'), this); ecModel.eachComponent('yAxis', createAxisCreator('y'), this); if (!axesCount.x || !axesCount.y) { // Roll back when there no either x or y axis this._axesMap = {}; this._axesList = []; return; } this._axesMap = axesMap; /// Create cartesian2d each$6(axesMap.x, function (xAxis, xAxisIndex) { each$6(axesMap.y, function (yAxis, yAxisIndex) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex; var cartesian = new Cartesian2D(key); cartesian.grid = this; cartesian.model = gridModel; this._coordsMap[key] = cartesian; this._coordsList.push(cartesian); cartesian.addAxis(xAxis); cartesian.addAxis(yAxis); }, this); }, this); function createAxisCreator(axisType) { return function (axisModel, idx) { if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) { return; } var axisPosition = axisModel.get('position'); if (axisType === 'x') { // Fix position if (axisPosition !== 'top' && axisPosition !== 'bottom') { // Default bottom of X axisPosition = 'bottom'; if (axisPositionUsed[axisPosition]) { axisPosition = axisPosition === 'top' ? 'bottom' : 'top'; } } } else { // Fix position if (axisPosition !== 'left' && axisPosition !== 'right') { // Default left of Y axisPosition = 'left'; if (axisPositionUsed[axisPosition]) { axisPosition = axisPosition === 'left' ? 'right' : 'left'; } } } axisPositionUsed[axisPosition] = true; var axis = new Axis2D( axisType, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition ); var isCategory = axis.type === 'category'; axis.onBand = isCategory && axisModel.get('boundaryGap'); axis.inverse = axisModel.get('inverse'); axis.onZero = axisModel.get('axisLine.onZero'); axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex'); // Inject axis into axisModel axisModel.axis = axis; // Inject axisModel into axis axis.model = axisModel; // Inject grid info axis axis.grid = this; // Index of axis, can be used as key axis.index = idx; this._axesList.push(axis); axesMap[axisType][idx] = axis; axesCount[axisType]++; }; } }; /** * Update cartesian properties from series * @param {module:echarts/model/Option} option * @private */ gridProto._updateScale = function (ecModel, gridModel) { // Reset scale each$1(this._axesList, function (axis) { axis.scale.setExtent(Infinity, -Infinity); }); ecModel.eachSeries(function (seriesModel) { if (isCartesian2D(seriesModel)) { var axesModels = findAxesModels(seriesModel, ecModel); var xAxisModel = axesModels[0]; var yAxisModel = axesModels[1]; if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel) ) { return; } var cartesian = this.getCartesian( xAxisModel.componentIndex, yAxisModel.componentIndex ); var data = seriesModel.getData(); var xAxis = cartesian.getAxis('x'); var yAxis = cartesian.getAxis('y'); if (data.type === 'list') { unionExtent(data, xAxis, seriesModel); unionExtent(data, yAxis, seriesModel); } } }, this); function unionExtent(data, axis, seriesModel) { each$6(data.mapDimension(axis.dim, true), function (dim) { axis.scale.unionExtentFromData(data, dim); }); } }; /** * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined * @return {Object} {baseAxes: [], otherAxes: []} */ gridProto.getTooltipAxes = function (dim) { var baseAxes = []; var otherAxes = []; each$6(this.getCartesians(), function (cartesian) { var baseAxis = (dim != null && dim !== 'auto') ? cartesian.getAxis(dim) : cartesian.getBaseAxis(); var otherAxis = cartesian.getOtherAxis(baseAxis); indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis); indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis); }); return {baseAxes: baseAxes, otherAxes: otherAxes}; }; /** * @inner */ function updateAxisTransform(axis, coordBase) { var axisExtent = axis.getExtent(); var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform axis.toGlobalCoord = axis.dim === 'x' ? function (coord) { return coord + coordBase; } : function (coord) { return axisExtentSum - coord + coordBase; }; axis.toLocalCoord = axis.dim === 'x' ? function (coord) { return coord - coordBase; } : function (coord) { return axisExtentSum - coord + coordBase; }; } var axesTypes = ['xAxis', 'yAxis']; /** * @inner */ function findAxesModels(seriesModel, ecModel) { return map(axesTypes, function (axisType) { var axisModel = seriesModel.getReferringComponents(axisType)[0]; if (__DEV__) { if (!axisModel) { throw new Error(axisType + ' "' + retrieve( seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0 ) + '" not found'); } } return axisModel; }); } /** * @inner */ function isCartesian2D(seriesModel) { return seriesModel.get('coordinateSystem') === 'cartesian2d'; } Grid.create = function (ecModel, api) { var grids = []; ecModel.eachComponent('grid', function (gridModel, idx) { var grid = new Grid(gridModel, ecModel, api); grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize // should be performed in create stage. grid.resize(gridModel, api, true); gridModel.coordinateSystem = grid; grids.push(grid); }); // Inject the coordinateSystems into seriesModel ecModel.eachSeries(function (seriesModel) { if (!isCartesian2D(seriesModel)) { return; } var axesModels = findAxesModels(seriesModel, ecModel); var xAxisModel = axesModels[0]; var yAxisModel = axesModels[1]; var gridModel = xAxisModel.getCoordSysModel(); if (__DEV__) { if (!gridModel) { throw new Error( 'Grid "' + retrieve( xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0 ) + '" not found' ); } if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) { throw new Error('xAxis and yAxis must use the same grid'); } } var grid = gridModel.coordinateSystem; seriesModel.coordinateSystem = grid.getCartesian( xAxisModel.componentIndex, yAxisModel.componentIndex ); }); return grids; }; // For deciding which dimensions to use when creating list data Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions; CoordinateSystemManager.register('cartesian2d', Grid); var PI$2 = Math.PI; function makeAxisEventDataBase(axisModel) { var eventData = { componentType: axisModel.mainType }; eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex; return eventData; } /** * A final axis is translated and rotated from a "standard axis". * So opt.position and opt.rotation is required. * * A standard axis is and axis from [0, 0] to [0, axisExtent[1]], * for example: (0, 0) ------------> (0, 50) * * nameDirection or tickDirection or labelDirection is 1 means tick * or label is below the standard axis, whereas is -1 means above * the standard axis. labelOffset means offset between label and axis, * which is useful when 'onZero', where axisLabel is in the grid and * label in outside grid. * * Tips: like always, * positive rotation represents anticlockwise, and negative rotation * represents clockwise. * The direction of position coordinate is the same as the direction * of screen coordinate. * * Do not need to consider axis 'inverse', which is auto processed by * axis extent. * * @param {module:zrender/container/Group} group * @param {Object} axisModel * @param {Object} opt Standard axis parameters. * @param {Array.<number>} opt.position [x, y] * @param {number} opt.rotation by radian * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'. * @param {number} [opt.tickDirection=1] 1 or -1 * @param {number} [opt.labelDirection=1] 1 or -1 * @param {number} [opt.labelOffset=0] Usefull when onZero. * @param {string} [opt.axisLabelShow] default get from axisModel. * @param {string} [opt.axisName] default get from axisModel. * @param {number} [opt.axisNameAvailableWidth] * @param {number} [opt.labelRotate] by degree, default get from axisModel. * @param {number} [opt.labelInterval] Default label interval when label * interval from model is null or 'auto'. * @param {number} [opt.strokeContainThreshold] Default label interval when label * @param {number} [opt.nameTruncateMaxWidth] */ var AxisBuilder = function (axisModel, opt) { /** * @readOnly */ this.opt = opt; /** * @readOnly */ this.axisModel = axisModel; // Default value defaults( opt, { labelOffset: 0, nameDirection: 1, tickDirection: 1, labelDirection: 1, silent: true } ); /** * @readOnly */ this.group = new Group(); // FIXME Not use a seperate text group? var dumbGroup = new Group({ position: opt.position.slice(), rotation: opt.rotation }); // this.group.add(dumbGroup); // this._dumbGroup = dumbGroup; dumbGroup.updateTransform(); this._transform = dumbGroup.transform; this._dumbGroup = dumbGroup; }; AxisBuilder.prototype = { constructor: AxisBuilder, hasBuilder: function (name) { return !!builders[name]; }, add: function (name) { builders[name].call(this); }, getGroup: function () { return this.group; } }; var builders = { /** * @private */ axisLine: function () { var opt = this.opt; var axisModel = this.axisModel; if (!axisModel.get('axisLine.show')) { return; } var extent = this.axisModel.axis.getExtent(); var matrix = this._transform; var pt1 = [extent[0], 0]; var pt2 = [extent[1], 0]; if (matrix) { applyTransform(pt1, pt1, matrix); applyTransform(pt2, pt2, matrix); } var lineStyle = extend( { lineCap: 'round' }, axisModel.getModel('axisLine.lineStyle').getLineStyle() ); this.group.add(new Line(subPixelOptimizeLine({ // Id for animation anid: 'line', shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: lineStyle, strokeContainThreshold: opt.strokeContainThreshold || 5, silent: true, z2: 1 }))); var arrows = axisModel.get('axisLine.symbol'); var arrowSize = axisModel.get('axisLine.symbolSize'); var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0; if (typeof arrowOffset === 'number') { arrowOffset = [arrowOffset, arrowOffset]; } if (arrows != null) { if (typeof arrows === 'string') { // Use the same arrow for start and end point arrows = [arrows, arrows]; } if (typeof arrowSize === 'string' || typeof arrowSize === 'number' ) { // Use the same size for width and height arrowSize = [arrowSize, arrowSize]; } var symbolWidth = arrowSize[0]; var symbolHeight = arrowSize[1]; each$1([{ rotate: opt.rotation + Math.PI / 2, offset: arrowOffset[0], r: 0 }, { rotate: opt.rotation - Math.PI / 2, offset: arrowOffset[1], r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1])) }], function (point, index) { if (arrows[index] !== 'none' && arrows[index] != null) { var symbol = createSymbol( arrows[index], -symbolWidth / 2, -symbolHeight / 2, symbolWidth, symbolHeight, lineStyle.stroke, true ); // Calculate arrow position with offset var r = point.r + point.offset; var pos = [ pt1[0] + r * Math.cos(opt.rotation), pt1[1] - r * Math.sin(opt.rotation) ]; symbol.attr({ rotation: point.rotate, position: pos, silent: true }); this.group.add(symbol); } }, this); } }, /** * @private */ axisTickLabel: function () { var axisModel = this.axisModel; var opt = this.opt; var tickEls = buildAxisTick(this, axisModel, opt); var labelEls = buildAxisLabel(this, axisModel, opt); fixMinMaxLabelShow(axisModel, labelEls, tickEls); }, /** * @private */ axisName: function () { var opt = this.opt; var axisModel = this.axisModel; var name = retrieve(opt.axisName, axisModel.get('name')); if (!name) { return; } var nameLocation = axisModel.get('nameLocation'); var nameDirection = opt.nameDirection; var textStyleModel = axisModel.getModel('nameTextStyle'); var gap = axisModel.get('nameGap') || 0; var extent = this.axisModel.axis.getExtent(); var gapSignal = extent[0] > extent[1] ? -1 : 1; var pos = [ nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // 'middle' // Reuse labelOffset. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0 ]; var labelLayout; var nameRotation = axisModel.get('nameRotate'); if (nameRotation != null) { nameRotation = nameRotation * PI$2 / 180; // To radian. } var axisNameAvailableWidth; if (isNameLocationCenter(nameLocation)) { labelLayout = innerTextLayout( opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis. nameDirection ); } else { labelLayout = endTextLayout( opt, nameLocation, nameRotation || 0, extent ); axisNameAvailableWidth = opt.axisNameAvailableWidth; if (axisNameAvailableWidth != null) { axisNameAvailableWidth = Math.abs( axisNameAvailableWidth / Math.sin(labelLayout.rotation) ); !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null); } } var textFont = textStyleModel.getFont(); var truncateOpt = axisModel.get('nameTruncate', true) || {}; var ellipsis = truncateOpt.ellipsis; var maxWidth = retrieve( opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth ); // FIXME // truncate rich text? (consider performance) var truncatedText = (ellipsis != null && maxWidth != null) ? truncateText$1( name, maxWidth, textFont, ellipsis, {minChar: 2, placeholder: truncateOpt.placeholder} ) : name; var tooltipOpt = axisModel.get('tooltip', true); var mainType = axisModel.mainType; var formatterParams = { componentType: mainType, name: name, $vars: ['name'] }; formatterParams[mainType + 'Index'] = axisModel.componentIndex; var textEl = new Text({ // Id for animation anid: 'name', __fullText: name, __truncatedText: truncatedText, position: pos, rotation: labelLayout.rotation, silent: isSilent(axisModel), z2: 1, tooltip: (tooltipOpt && tooltipOpt.show) ? extend({ content: name, formatter: function () { return name; }, formatterParams: formatterParams }, tooltipOpt) : null }); setTextStyle(textEl.style, textStyleModel, { text: truncatedText, textFont: textFont, textFill: textStyleModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'), textAlign: labelLayout.textAlign, textVerticalAlign: labelLayout.textVerticalAlign }); if (axisModel.get('triggerEvent')) { textEl.eventData = makeAxisEventDataBase(axisModel); textEl.eventData.targetType = 'axisName'; textEl.eventData.name = name; } // FIXME this._dumbGroup.add(textEl); textEl.updateTransform(); this.group.add(textEl); textEl.decomposeTransform(); } }; /** * @public * @static * @param {Object} opt * @param {number} axisRotation in radian * @param {number} textRotation in radian * @param {number} direction * @return {Object} { * rotation, // according to axis * textAlign, * textVerticalAlign * } */ var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) { var rotationDiff = remRadian(textRotation - axisRotation); var textAlign; var textVerticalAlign; if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line. textVerticalAlign = direction > 0 ? 'top' : 'bottom'; textAlign = 'center'; } else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line. textVerticalAlign = direction > 0 ? 'bottom' : 'top'; textAlign = 'center'; } else { textVerticalAlign = 'middle'; if (rotationDiff > 0 && rotationDiff < PI$2) { textAlign = direction > 0 ? 'right' : 'left'; } else { textAlign = direction > 0 ? 'left' : 'right'; } } return { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; }; function endTextLayout(opt, textPosition, textRotate, extent) { var rotationDiff = remRadian(textRotate - opt.rotation); var textAlign; var textVerticalAlign; var inverse = extent[0] > extent[1]; var onLeft = (textPosition === 'start' && !inverse) || (textPosition !== 'start' && inverse); if (isRadianAroundZero(rotationDiff - PI$2 / 2)) { textVerticalAlign = onLeft ? 'bottom' : 'top'; textAlign = 'center'; } else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) { textVerticalAlign = onLeft ? 'top' : 'bottom'; textAlign = 'center'; } else { textVerticalAlign = 'middle'; if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) { textAlign = onLeft ? 'left' : 'right'; } else { textAlign = onLeft ? 'right' : 'left'; } } return { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } function isSilent(axisModel) { var tooltipOpt = axisModel.get('tooltip'); return axisModel.get('silent') // Consider mouse cursor, add these restrictions. || !( axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show) ); } function fixMinMaxLabelShow(axisModel, labelEls, tickEls) { // If min or max are user set, we need to check // If the tick on min(max) are overlap on their neighbour tick // If they are overlapped, we need to hide the min(max) tick label var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); // FIXME // Have not consider onBand yet, where tick els is more than label els. labelEls = labelEls || []; tickEls = tickEls || []; var firstLabel = labelEls[0]; var nextLabel = labelEls[1]; var lastLabel = labelEls[labelEls.length - 1]; var prevLabel = labelEls[labelEls.length - 2]; var firstTick = tickEls[0]; var nextTick = tickEls[1]; var lastTick = tickEls[tickEls.length - 1]; var prevTick = tickEls[tickEls.length - 2]; if (showMinLabel === false) { ignoreEl(firstLabel); ignoreEl(firstTick); } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) { if (showMinLabel) { ignoreEl(nextLabel); ignoreEl(nextTick); } else { ignoreEl(firstLabel); ignoreEl(firstTick); } } if (showMaxLabel === false) { ignoreEl(lastLabel); ignoreEl(lastTick); } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) { if (showMaxLabel) { ignoreEl(prevLabel); ignoreEl(prevTick); } else { ignoreEl(lastLabel); ignoreEl(lastTick); } } } function ignoreEl(el) { el && (el.ignore = true); } function isTwoLabelOverlapped(current, next, labelLayout) { // current and next has the same rotation. var firstRect = current && current.getBoundingRect().clone(); var nextRect = next && next.getBoundingRect().clone(); if (!firstRect || !nextRect) { return; } // When checking intersect of two rotated labels, we use mRotationBack // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`. var mRotationBack = identity([]); rotate(mRotationBack, mRotationBack, -current.rotation); firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform())); nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform())); return firstRect.intersect(nextRect); } function isNameLocationCenter(nameLocation) { return nameLocation === 'middle' || nameLocation === 'center'; } /** * @static */ var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function ( axis, i, interval, ticksCnt, showMinLabel, showMaxLabel ) { if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) { return false; } // FIXME // Have not consider label overlap (if label is too long) yet. var rawTick; var scale$$1 = axis.scale; return scale$$1.type === 'ordinal' && ( typeof interval === 'function' ? ( rawTick = scale$$1.getTicks()[i], !interval(rawTick, scale$$1.getLabel(rawTick)) ) : i % (interval + 1) ); }; /** * @static */ var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) { var interval = model.get('interval'); if (interval == null || interval == 'auto') { interval = labelInterval; } return interval; }; function buildAxisTick(axisBuilder, axisModel, opt) { var axis = axisModel.axis; if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) { return; } var tickModel = axisModel.getModel('axisTick'); var lineStyleModel = tickModel.getModel('lineStyle'); var tickLen = tickModel.get('length'); var tickInterval = getInterval$1(tickModel, opt.labelInterval); var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel')); // FIXME // Corresponds to ticksCoords ? var ticks = axis.scale.getTicks(); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); var pt1 = []; var pt2 = []; var matrix = axisBuilder._transform; var tickEls = []; var ticksCnt = ticksCoords.length; for (var i = 0; i < ticksCnt; i++) { // Only ordinal scale support tick interval if (ifIgnoreOnTick$1( axis, i, tickInterval, ticksCnt, showMinLabel, showMaxLabel )) { continue; } var tickCoord = ticksCoords[i]; pt1[0] = tickCoord; pt1[1] = 0; pt2[0] = tickCoord; pt2[1] = opt.tickDirection * tickLen; if (matrix) { applyTransform(pt1, pt1, matrix); applyTransform(pt2, pt2, matrix); } // Tick line, Not use group transform to have better line draw var tickEl = new Line(subPixelOptimizeLine({ // Id for animation anid: 'tick_' + ticks[i], shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: defaults( lineStyleModel.getLineStyle(), { stroke: axisModel.get('axisLine.lineStyle.color') } ), z2: 2, silent: true })); axisBuilder.group.add(tickEl); tickEls.push(tickEl); } return tickEls; } function buildAxisLabel(axisBuilder, axisModel, opt) { var axis = axisModel.axis; var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show')); if (!show || axis.scale.isBlank()) { return; } var labelModel = axisModel.getModel('axisLabel'); var labelMargin = labelModel.get('margin'); var ticks = axis.scale.getTicks(); var labels = axisModel.getFormattedLabels(); // Special label rotate. var labelRotation = ( retrieve(opt.labelRotate, labelModel.get('rotate')) || 0 ) * PI$2 / 180; var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection); var categoryData = axisModel.getCategories(); var labelEls = []; var silent = isSilent(axisModel); var triggerEvent = axisModel.get('triggerEvent'); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); each$1(ticks, function (tickVal, index) { if (ifIgnoreOnTick$1( axis, index, opt.labelInterval, ticks.length, showMinLabel, showMaxLabel )) { return; } var itemLabelModel = labelModel; if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) { itemLabelModel = new Model( categoryData[tickVal].textStyle, labelModel, axisModel.ecModel ); } var textColor = itemLabelModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'); var tickCoord = axis.dataToCoord(tickVal); var pos = [ tickCoord, opt.labelOffset + opt.labelDirection * labelMargin ]; var labelStr = axis.scale.getLabel(tickVal); var textEl = new Text({ // Id for animation anid: 'label_' + tickVal, position: pos, rotation: labelLayout.rotation, silent: silent, z2: 10 }); setTextStyle(textEl.style, itemLabelModel, { text: labels[index], textAlign: itemLabelModel.getShallow('align', true) || labelLayout.textAlign, textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign, textFill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original // index of axis.data. So tick should not be exposed to user // in category axis. // (2) Compatible with previous version, which always returns labelStr. // But in interval scale labelStr is like '223,445', which maked // user repalce ','. So we modify it to return original val but remain // it as 'string' to avoid error in replacing. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal, index ) : textColor }); // Pack data for mouse event if (triggerEvent) { textEl.eventData = makeAxisEventDataBase(axisModel); textEl.eventData.targetType = 'axisLabel'; textEl.eventData.value = labelStr; } // FIXME axisBuilder._dumbGroup.add(textEl); textEl.updateTransform(); labelEls.push(textEl); axisBuilder.group.add(textEl); textEl.decomposeTransform(); }); return labelEls; } // Build axisPointerModel, mergin tooltip.axisPointer model for each axis. // allAxesInfo should be updated when setOption performed. function fixValue(axisModel) { var axisInfo = getAxisInfo(axisModel); if (!axisInfo) { return; } var axisPointerModel = axisInfo.axisPointerModel; var scale = axisInfo.axis.scale; var option = axisPointerModel.option; var status = axisPointerModel.get('status'); var value = axisPointerModel.get('value'); // Parse init value for category and time axis. if (value != null) { value = scale.parse(value); } var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value // and status should be initialized. if (status == null) { option.status = useHandle ? 'show' : 'hide'; } var extent = scale.getExtent().slice(); extent[0] > extent[1] && extent.reverse(); if (// Pick a value on axis when initializing. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent, // where we should re-pick a value to keep `handle` displaying normally. || value > extent[1] ) { // Make handle displayed on the end of the axis when init, which looks better. value = extent[1]; } if (value < extent[0]) { value = extent[0]; } option.value = value; if (useHandle) { option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show'; } } function getAxisInfo(axisModel) { var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo; return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)]; } function getAxisPointerModel(axisModel) { var axisInfo = getAxisInfo(axisModel); return axisInfo && axisInfo.axisPointerModel; } function isHandleTrigger(axisPointerModel) { return !!axisPointerModel.get('handle.show'); } /** * @param {module:echarts/model/Model} model * @return {string} unique key */ function makeKey(model) { return model.type + '||' + model.id; } /** * Base class of AxisView. */ var AxisView = extendComponentView({ type: 'axis', /** * @private */ _axisPointer: null, /** * @protected * @type {string} */ axisPointerClass: null, /** * @override */ render: function (axisModel, ecModel, api, payload) { // FIXME // This process should proformed after coordinate systems updated // (axis scale updated), and should be performed each time update. // So put it here temporarily, although it is not appropriate to // put a model-writing procedure in `view`. this.axisPointerClass && fixValue(axisModel); AxisView.superApply(this, 'render', arguments); updateAxisPointer(this, axisModel, ecModel, api, payload, true); }, /** * Action handler. * @public * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ updateAxisPointer: function (axisModel, ecModel, api, payload, force) { updateAxisPointer(this, axisModel, ecModel, api, payload, false); }, /** * @override */ remove: function (ecModel, api) { var axisPointer = this._axisPointer; axisPointer && axisPointer.remove(api); AxisView.superApply(this, 'remove', arguments); }, /** * @override */ dispose: function (ecModel, api) { disposeAxisPointer(this, api); AxisView.superApply(this, 'dispose', arguments); } }); function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) { var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass); if (!Clazz) { return; } var axisPointerModel = getAxisPointerModel(axisModel); axisPointerModel ? (axisView._axisPointer || (axisView._axisPointer = new Clazz())) .render(axisModel, axisPointerModel, api, forceRender) : disposeAxisPointer(axisView, api); } function disposeAxisPointer(axisView, ecModel, api) { var axisPointer = axisView._axisPointer; axisPointer && axisPointer.dispose(ecModel, api); axisView._axisPointer = null; } var axisPointerClazz = []; AxisView.registerAxisPointerClass = function (type, clazz) { if (__DEV__) { if (axisPointerClazz[type]) { throw new Error('axisPointer ' + type + ' exists'); } } axisPointerClazz[type] = clazz; }; AxisView.getAxisPointerClass = function (type) { return type && axisPointerClazz[type]; }; /** * @param {Object} opt {labelInside} * @return {Object} { * position, rotation, labelDirection, labelOffset, * tickDirection, labelRotate, labelInterval, z2 * } */ function layout$1(gridModel, axisModel, opt) { opt = opt || {}; var grid = gridModel.coordinateSystem; var axis = axisModel.axis; var layout = {}; var rawAxisPosition = axis.position; var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition; var axisDim = axis.dim; var rect = grid.getRect(); var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height]; var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2}; var axisOffset = axisModel.get('offset') || 0; var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset]; if (axis.onZero) { var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex); var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0)); posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]); } // Axis position layout.position = [ axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3] ]; // Axis rotation layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim var dirMap = {top: -1, bottom: 1, left: -1, right: 1}; layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition]; layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0; if (axisModel.get('axisTick.inside')) { layout.tickDirection = -layout.tickDirection; } if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) { layout.labelDirection = -layout.labelDirection; } // Special label rotation var labelRotate = axisModel.get('axisLabel.rotate'); layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // label interval when auto mode. layout.labelInterval = axis.getLabelInterval(); // Over splitLine and splitArea layout.z2 = 1; return layout; } var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick; var getInterval = AxisBuilder.getInterval; var axisBuilderAttrs = [ 'axisLine', 'axisTickLabel', 'axisName' ]; var selfBuilderAttrs = [ 'splitArea', 'splitLine' ]; // function getAlignWithLabel(model, axisModel) { // var alignWithLabel = model.get('alignWithLabel'); // if (alignWithLabel === 'auto') { // alignWithLabel = axisModel.get('axisTick.alignWithLabel'); // } // return alignWithLabel; // } var CartesianAxisView = AxisView.extend({ type: 'cartesianAxis', axisPointerClass: 'CartesianAxisPointer', /** * @override */ render: function (axisModel, ecModel, api, payload) { this.group.removeAll(); var oldAxisGroup = this._axisGroup; this._axisGroup = new Group(); this.group.add(this._axisGroup); if (!axisModel.get('show')) { return; } var gridModel = axisModel.getCoordSysModel(); var layout = layout$1(gridModel, axisModel); var axisBuilder = new AxisBuilder(axisModel, layout); each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder); this._axisGroup.add(axisBuilder.getGroup()); each$1(selfBuilderAttrs, function (name) { if (axisModel.get(name + '.show')) { this['_' + name](axisModel, gridModel, layout.labelInterval); } }, this); groupTransition(oldAxisGroup, this._axisGroup, axisModel); CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload); }, /** * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {number|Function} labelInterval * @private */ _splitLine: function (axisModel, gridModel, labelInterval) { var axis = axisModel.axis; if (axis.scale.isBlank()) { return; } var splitLineModel = axisModel.getModel('splitLine'); var lineStyleModel = splitLineModel.getModel('lineStyle'); var lineColors = lineStyleModel.get('color'); var lineInterval = getInterval(splitLineModel, labelInterval); lineColors = isArray(lineColors) ? lineColors : [lineColors]; var gridRect = gridModel.coordinateSystem.getRect(); var isHorizontal = axis.isHorizontal(); var lineCount = 0; var ticksCoords = axis.getTicksCoords( // splitLineModel.get('alignWithLabel') ); var ticks = axis.scale.getTicks(); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); var p1 = []; var p2 = []; // Simple optimization // Batching the lines if color are the same var lineStyle = lineStyleModel.getLineStyle(); for (var i = 0; i < ticksCoords.length; i++) { if (ifIgnoreOnTick( axis, i, lineInterval, ticksCoords.length, showMinLabel, showMaxLabel )) { continue; } var tickCoord = axis.toGlobalCoord(ticksCoords[i]); if (isHorizontal) { p1[0] = tickCoord; p1[1] = gridRect.y; p2[0] = tickCoord; p2[1] = gridRect.y + gridRect.height; } else { p1[0] = gridRect.x; p1[1] = tickCoord; p2[0] = gridRect.x + gridRect.width; p2[1] = tickCoord; } var colorIndex = (lineCount++) % lineColors.length; this._axisGroup.add(new Line(subPixelOptimizeLine({ anid: 'line_' + ticks[i], shape: { x1: p1[0], y1: p1[1], x2: p2[0], y2: p2[1] }, style: defaults({ stroke: lineColors[colorIndex] }, lineStyle), silent: true }))); } }, /** * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {number|Function} labelInterval * @private */ _splitArea: function (axisModel, gridModel, labelInterval) { var axis = axisModel.axis; if (axis.scale.isBlank()) { return; } var splitAreaModel = axisModel.getModel('splitArea'); var areaStyleModel = splitAreaModel.getModel('areaStyle'); var areaColors = areaStyleModel.get('color'); var gridRect = gridModel.coordinateSystem.getRect(); var ticksCoords = axis.getTicksCoords( // splitAreaModel.get('alignWithLabel') ); var ticks = axis.scale.getTicks(); var prevX = axis.toGlobalCoord(ticksCoords[0]); var prevY = axis.toGlobalCoord(ticksCoords[0]); var count = 0; var areaInterval = getInterval(splitAreaModel, labelInterval); var areaStyle = areaStyleModel.getAreaStyle(); areaColors = isArray(areaColors) ? areaColors : [areaColors]; var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); for (var i = 1; i < ticksCoords.length; i++) { if (ifIgnoreOnTick( axis, i, areaInterval, ticksCoords.length, showMinLabel, showMaxLabel ) && (i < ticksCoords.length - 1)) { continue; } var tickCoord = axis.toGlobalCoord(ticksCoords[i]); var x; var y; var width; var height; if (axis.isHorizontal()) { x = prevX; y = gridRect.y; width = tickCoord - x; height = gridRect.height; } else { x = gridRect.x; y = prevY; width = gridRect.width; height = tickCoord - y; } var colorIndex = (count++) % areaColors.length; this._axisGroup.add(new Rect({ anid: 'area_' + ticks[i], shape: { x: x, y: y, width: width, height: height }, style: defaults({ fill: areaColors[colorIndex] }, areaStyle), silent: true })); prevX = x + width; prevY = y + height; } } }); CartesianAxisView.extend({ type: 'xAxis' }); CartesianAxisView.extend({ type: 'yAxis' }); // Grid view extendComponentView({ type: 'grid', render: function (gridModel, ecModel) { this.group.removeAll(); if (gridModel.get('show')) { this.group.add(new Rect({ shape: gridModel.coordinateSystem.getRect(), style: defaults({ fill: gridModel.get('backgroundColor') }, gridModel.getItemStyle()), silent: true, z2: -1 })); } } }); registerPreprocessor(function (option) { // Only create grid when need if (option.xAxis && option.yAxis && !option.grid) { option.grid = {}; } }); // In case developer forget to include grid component registerVisual(visualSymbol('line', 'circle', 'line')); registerLayout(layoutPoints('line')); // Down sample after filter registerProcessor( PRIORITY.PROCESSOR.STATISTIC, dataSample('line') ); var BaseBarSeries = SeriesModel.extend({ type: 'series.__base_bar__', getInitialData: function (option, ecModel) { return createListFromArray(this.getSource(), this); }, getMarkerPosition: function (value) { var coordSys = this.coordinateSystem; if (coordSys) { // PENDING if clamp ? var pt = coordSys.dataToPoint(coordSys.clampData(value)); var data = this.getData(); var offset = data.getLayout('offset'); var size = data.getLayout('size'); var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1; pt[offsetIndex] += offset + size / 2; return pt; } return [NaN, NaN]; }, defaultOption: { zlevel: 0, // 一级层叠 z: 2, // 二级层叠 coordinateSystem: 'cartesian2d', legendHoverLink: true, // stack: null // Cartesian coordinate system // xAxisIndex: 0, // yAxisIndex: 0, // 最小高度改为0 barMinHeight: 0, // 最小角度为0,仅对极坐标系下的柱状图有效 barMinAngle: 0, // cursor: null, // barMaxWidth: null, // 默认自适应 // barWidth: null, // 柱间距离,默认为柱形宽度的30%,可设固定值 // barGap: '30%', // 类目间柱形距离,默认为类目间距的20%,可设固定值 // barCategoryGap: '20%', // label: { // show: false // }, itemStyle: {}, emphasis: {} } }); BaseBarSeries.extend({ type: 'series.bar', dependencies: ['grid', 'polar'], brushSelector: 'rect' }); function setLabel( normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside ) { var labelModel = itemModel.getModel('label'); var hoverLabelModel = itemModel.getModel('emphasis.label'); setLabelStyle( normalStyle, hoverStyle, labelModel, hoverLabelModel, { labelFetcher: seriesModel, labelDataIndex: dataIndex, defaultText: getDefaultLabel(seriesModel.getData(), dataIndex), isRectText: true, autoColor: color } ); fixPosition(normalStyle); fixPosition(hoverStyle); } function fixPosition(style, labelPositionOutside) { if (style.textPosition === 'outside') { style.textPosition = labelPositionOutside; } } var getBarItemStyle = makeStyleMapper( [ ['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], // Compatitable with 2 ['stroke', 'barBorderColor'], ['lineWidth', 'barBorderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] ] ); var barItemStyle = { getBarItemStyle: function (excludes) { var style = getBarItemStyle(this, excludes); if (this.getBorderLineDash) { var lineDash = this.getBorderLineDash(); lineDash && (style.lineDash = lineDash); } return style; } }; var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth']; // FIXME // Just for compatible with ec2. extend(Model.prototype, barItemStyle); extendChartView({ type: 'bar', render: function (seriesModel, ecModel, api) { var coordinateSystemType = seriesModel.get('coordinateSystem'); if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar' ) { this._render(seriesModel, ecModel, api); } else if (__DEV__) { console.warn('Only cartesian2d and polar supported for bar.'); } return this.group; }, dispose: noop, _render: function (seriesModel, ecModel, api) { var group = this.group; var data = seriesModel.getData(); var oldData = this._data; var coord = seriesModel.coordinateSystem; var baseAxis = coord.getBaseAxis(); var isHorizontalOrRadial; if (coord.type === 'cartesian2d') { isHorizontalOrRadial = baseAxis.isHorizontal(); } else if (coord.type === 'polar') { isHorizontalOrRadial = baseAxis.dim === 'angle'; } var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null; data.diff(oldData) .add(function (dataIndex) { if (!data.hasValue(dataIndex)) { return; } var itemModel = data.getItemModel(dataIndex); var layout = getLayout[coord.type](data, dataIndex, itemModel); var el = elementCreator[coord.type]( data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel ); data.setItemGraphicEl(dataIndex, el); group.add(el); updateStyle( el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar' ); }) .update(function (newIndex, oldIndex) { var el = oldData.getItemGraphicEl(oldIndex); if (!data.hasValue(newIndex)) { group.remove(el); return; } var itemModel = data.getItemModel(newIndex); var layout = getLayout[coord.type](data, newIndex, itemModel); if (el) { updateProps(el, {shape: layout}, animationModel, newIndex); } else { el = elementCreator[coord.type]( data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true ); } data.setItemGraphicEl(newIndex, el); // Add back group.add(el); updateStyle( el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar' ); }) .remove(function (dataIndex) { var el = oldData.getItemGraphicEl(dataIndex); if (coord.type === 'cartesian2d') { el && removeRect(dataIndex, animationModel, el); } else { el && removeSector(dataIndex, animationModel, el); } }) .execute(); this._data = data; }, remove: function (ecModel, api) { var group = this.group; var data = this._data; if (ecModel.get('animation')) { if (data) { data.eachItemGraphicEl(function (el) { if (el.type === 'sector') { removeSector(el.dataIndex, ecModel, el); } else { removeRect(el.dataIndex, ecModel, el); } }); } } else { group.removeAll(); } } }); var elementCreator = { cartesian2d: function ( data, dataIndex, itemModel, layout, isHorizontal, animationModel, isUpdate ) { var rect = new Rect({shape: extend({}, layout)}); // Animation if (animationModel) { var rectShape = rect.shape; var animateProperty = isHorizontal ? 'height' : 'width'; var animateTarget = {}; rectShape[animateProperty] = 0; animateTarget[animateProperty] = layout[animateProperty]; graphic[isUpdate ? 'updateProps' : 'initProps'](rect, { shape: animateTarget }, animationModel, dataIndex); } return rect; }, polar: function ( data, dataIndex, itemModel, layout, isRadial, animationModel, isUpdate ) { // Keep the same logic with bar in catesion: use end value to control // direction. Notice that if clockwise is true (by default), the sector // will always draw clockwisely, no matter whether endAngle is greater // or less than startAngle. var clockwise = layout.startAngle < layout.endAngle; var sector = new Sector({ shape: defaults({clockwise: clockwise}, layout) }); // Animation if (animationModel) { var sectorShape = sector.shape; var animateProperty = isRadial ? 'r' : 'endAngle'; var animateTarget = {}; sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle; animateTarget[animateProperty] = layout[animateProperty]; graphic[isUpdate ? 'updateProps' : 'initProps'](sector, { shape: animateTarget }, animationModel, dataIndex); } return sector; } }; function removeRect(dataIndex, animationModel, el) { // Not show text when animating el.style.text = null; updateProps(el, { shape: { width: 0 } }, animationModel, dataIndex, function () { el.parent && el.parent.remove(el); }); } function removeSector(dataIndex, animationModel, el) { // Not show text when animating el.style.text = null; updateProps(el, { shape: { r: el.shape.r0 } }, animationModel, dataIndex, function () { el.parent && el.parent.remove(el); }); } var getLayout = { cartesian2d: function (data, dataIndex, itemModel) { var layout = data.getItemLayout(dataIndex); var fixedLineWidth = getLineWidth(itemModel, layout); // fix layout with lineWidth var signX = layout.width > 0 ? 1 : -1; var signY = layout.height > 0 ? 1 : -1; return { x: layout.x + signX * fixedLineWidth / 2, y: layout.y + signY * fixedLineWidth / 2, width: layout.width - signX * fixedLineWidth, height: layout.height - signY * fixedLineWidth }; }, polar: function (data, dataIndex, itemModel) { var layout = data.getItemLayout(dataIndex); return { cx: layout.cx, cy: layout.cy, r0: layout.r0, r: layout.r, startAngle: layout.startAngle, endAngle: layout.endAngle }; } }; function updateStyle( el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar ) { var color = data.getItemVisual(dataIndex, 'color'); var opacity = data.getItemVisual(dataIndex, 'opacity'); var itemStyleModel = itemModel.getModel('itemStyle'); var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle(); if (!isPolar) { el.setShape('r', itemStyleModel.get('barBorderRadius') || 0); } el.useStyle(defaults( { fill: color, opacity: opacity }, itemStyleModel.getBarItemStyle() )); var cursorStyle = itemModel.getShallow('cursor'); cursorStyle && el.attr('cursor', cursorStyle); var labelPositionOutside = isHorizontal ? (layout.height > 0 ? 'bottom' : 'top') : (layout.width > 0 ? 'left' : 'right'); if (!isPolar) { setLabel( el.style, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside ); } setHoverStyle(el, hoverStyle); } // In case width or height are too small. function getLineWidth(itemModel, rawLayout) { var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height)); } // In case developer forget to include grid component registerLayout(curry(layout, 'bar')); // Visual coding for legend registerVisual(function (ecModel) { ecModel.eachSeriesByType('bar', function (seriesModel) { var data = seriesModel.getData(); data.setVisual('legendSymbol', 'roundRect'); }); }); /** * [Usage]: * (1) * createListSimply(seriesModel, ['value']); * (2) * createListSimply(seriesModel, { * coordDimensions: ['value'], * dimensionsCount: 5 * }); * * @param {module:echarts/model/Series} seriesModel * @param {Object|Array.<string|Object>} opt opt or coordDimensions * The options in opt, see `echarts/data/helper/createDimensions` * @param {Array.<string>} [nameList] * @return {module:echarts/data/List} */ var createListSimply = function (seriesModel, opt, nameList) { opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt); var source = seriesModel.getSource(); var dimensionsInfo = createDimensions(source, opt); var list = new List(dimensionsInfo, seriesModel); list.initData(source, nameList); return list; }; /** * Data selectable mixin for chart series. * To eanble data select, option of series must have `selectedMode`. * And each data item will use `selected` to toggle itself selected status */ var dataSelectableMixin = { /** * @param {Array.<Object>} targetList [{name, value, selected}, ...] * If targetList is an array, it should like [{name: ..., value: ...}, ...]. * If targetList is a "List", it must have coordDim: 'value' dimension and name. */ updateSelectedMap: function (targetList) { this._targetList = isArray(targetList) ? targetList.slice() : []; this._selectTargetMap = reduce(targetList || [], function (targetMap, target) { targetMap.set(target.name, target); return targetMap; }, createHashMap()); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ // PENGING If selectedMode is null ? select: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); var selectedMode = this.get('selectedMode'); if (selectedMode === 'single') { this._selectTargetMap.each(function (target) { target.selected = false; }); } target && (target.selected = true); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ unSelect: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); // var selectedMode = this.get('selectedMode'); // selectedMode !== 'single' && target && (target.selected = false); target && (target.selected = false); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ toggleSelected: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); if (target != null) { this[target.selected ? 'unSelect' : 'select'](name, id); return target.selected; } }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ isSelected: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); return target && target.selected; } }; var PieSeries = extendSeriesModel({ type: 'series.pie', // Overwrite init: function (option) { PieSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item // Use a function instead of direct access because data reference may changed this.legendDataProvider = function () { return this.getRawData(); }; this.updateSelectedMap(this._createSelectableList()); this._defaultLabelLine(option); }, // Overwrite mergeOption: function (newOption) { PieSeries.superCall(this, 'mergeOption', newOption); this.updateSelectedMap(this._createSelectableList()); }, getInitialData: function (option, ecModel) { return createListSimply(this, ['value']); }, _createSelectableList: function () { var data = this.getRawData(); var valueDim = data.mapDimension('value'); var targetList = []; for (var i = 0, len = data.count(); i < len; i++) { targetList.push({ name: data.getName(i), value: data.get(valueDim, i), selected: retrieveRawAttr(data, i, 'selected') }); } return targetList; }, // Overwrite getDataParams: function (dataIndex) { var data = this.getData(); var params = PieSeries.superCall(this, 'getDataParams', dataIndex); // FIXME toFixed? var valueList = []; data.each(data.mapDimension('value'), function (value) { valueList.push(value); }); params.percent = getPercentWithPrecision( valueList, dataIndex, data.hostModel.get('percentPrecision') ); params.$vars.push('percent'); return params; }, _defaultLabelLine: function (option) { // Extend labelLine emphasis defaultEmphasis(option, 'labelLine', ['show']); var labelLineNormalOpt = option.labelLine; var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false` labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show; labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show; }, defaultOption: { zlevel: 0, z: 2, legendHoverLink: true, hoverAnimation: true, // 默认全局居中 center: ['50%', '50%'], radius: [0, '75%'], // 默认顺时针 clockwise: true, startAngle: 90, // 最小角度改为0 minAngle: 0, // 选中时扇区偏移量 selectedOffset: 10, // 高亮扇区偏移量 hoverOffset: 10, // If use strategy to avoid label overlapping avoidLabelOverlap: true, // 选择模式,默认关闭,可选single,multiple // selectedMode: false, // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积) // roseType: null, percentPrecision: 2, // If still show when all data zero. stillShowZeroSum: true, // cursor: null, label: { // If rotate around circle rotate: false, show: true, // 'outer', 'inside', 'center' position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调 // 默认使用全局文本样式,详见TEXTSTYLE // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数 }, // Enabled when label.normal.position is 'outer' labelLine: { show: true, // 引导线两段中的第一段长度 length: 15, // 引导线两段中的第二段长度 length2: 15, smooth: false, lineStyle: { // color: 各异, width: 1, type: 'solid' } }, itemStyle: { borderWidth: 1 }, // Animation type canbe expansion, scale animationType: 'expansion', animationEasing: 'cubicOut' } }); mixin(PieSeries, dataSelectableMixin); /** * @param {module:echarts/model/Series} seriesModel * @param {boolean} hasAnimation * @inner */ function updateDataSelected(uid, seriesModel, hasAnimation, api) { var data = seriesModel.getData(); var dataIndex = this.dataIndex; var name = data.getName(dataIndex); var selectedOffset = seriesModel.get('selectedOffset'); api.dispatchAction({ type: 'pieToggleSelect', from: uid, name: name, seriesId: seriesModel.id }); data.each(function (idx) { toggleItemSelected( data.getItemGraphicEl(idx), data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), selectedOffset, hasAnimation ); }); } /** * @param {module:zrender/graphic/Sector} el * @param {Object} layout * @param {boolean} isSelected * @param {number} selectedOffset * @param {boolean} hasAnimation * @inner */ function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) { var midAngle = (layout.startAngle + layout.endAngle) / 2; var dx = Math.cos(midAngle); var dy = Math.sin(midAngle); var offset = isSelected ? selectedOffset : 0; var position = [dx * offset, dy * offset]; hasAnimation // animateTo will stop revious animation like update transition ? el.animate() .when(200, { position: position }) .start('bounceOut') : el.attr('position', position); } /** * Piece of pie including Sector, Label, LabelLine * @constructor * @extends {module:zrender/graphic/Group} */ function PiePiece(data, idx) { Group.call(this); var sector = new Sector({ z2: 2 }); var polyline = new Polyline(); var text = new Text(); this.add(sector); this.add(polyline); this.add(text); this.updateData(data, idx, true); // Hover to change label and labelLine function onEmphasis() { polyline.ignore = polyline.hoverIgnore; text.ignore = text.hoverIgnore; } function onNormal() { polyline.ignore = polyline.normalIgnore; text.ignore = text.normalIgnore; } this.on('emphasis', onEmphasis) .on('normal', onNormal) .on('mouseover', onEmphasis) .on('mouseout', onNormal); } var piePieceProto = PiePiece.prototype; piePieceProto.updateData = function (data, idx, firstCreate) { var sector = this.childAt(0); var seriesModel = data.hostModel; var itemModel = data.getItemModel(idx); var layout = data.getItemLayout(idx); var sectorShape = extend({}, layout); sectorShape.label = null; if (firstCreate) { sector.setShape(sectorShape); var animationType = seriesModel.getShallow('animationType'); if (animationType === 'scale') { sector.shape.r = layout.r0; initProps(sector, { shape: { r: layout.r } }, seriesModel, idx); } // Expansion else { sector.shape.endAngle = layout.startAngle; updateProps(sector, { shape: { endAngle: layout.endAngle } }, seriesModel, idx); } } else { updateProps(sector, { shape: sectorShape }, seriesModel, idx); } // Update common style var visualColor = data.getItemVisual(idx, 'color'); sector.useStyle( defaults( { lineJoin: 'bevel', fill: visualColor }, itemModel.getModel('itemStyle').getItemStyle() ) ); sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle(); var cursorStyle = itemModel.getShallow('cursor'); cursorStyle && sector.attr('cursor', cursorStyle); // Toggle selected toggleItemSelected( this, data.getItemLayout(idx), seriesModel.isSelected(null, idx), seriesModel.get('selectedOffset'), seriesModel.get('animation') ); function onEmphasis() { // Sector may has animation of updating data. Force to move to the last frame // Or it may stopped on the wrong shape sector.stopAnimation(true); sector.animateTo({ shape: { r: layout.r + seriesModel.get('hoverOffset') } }, 300, 'elasticOut'); } function onNormal() { sector.stopAnimation(true); sector.animateTo({ shape: { r: layout.r } }, 300, 'elasticOut'); } sector.off('mouseover').off('mouseout').off('emphasis').off('normal'); if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) { sector .on('mouseover', onEmphasis) .on('mouseout', onNormal) .on('emphasis', onEmphasis) .on('normal', onNormal); } this._updateLabel(data, idx); setHoverStyle(this); }; piePieceProto._updateLabel = function (data, idx) { var labelLine = this.childAt(1); var labelText = this.childAt(2); var seriesModel = data.hostModel; var itemModel = data.getItemModel(idx); var layout = data.getItemLayout(idx); var labelLayout = layout.label; var visualColor = data.getItemVisual(idx, 'color'); updateProps(labelLine, { shape: { points: labelLayout.linePoints || [ [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y] ] } }, seriesModel, idx); updateProps(labelText, { style: { x: labelLayout.x, y: labelLayout.y } }, seriesModel, idx); labelText.attr({ rotation: labelLayout.rotation, origin: [labelLayout.x, labelLayout.y], z2: 10 }); var labelModel = itemModel.getModel('label'); var labelHoverModel = itemModel.getModel('emphasis.label'); var labelLineModel = itemModel.getModel('labelLine'); var labelLineHoverModel = itemModel.getModel('emphasis.labelLine'); var visualColor = data.getItemVisual(idx, 'color'); setLabelStyle( labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel, { labelFetcher: data.hostModel, labelDataIndex: idx, defaultText: data.getName(idx), autoColor: visualColor, useInsideStyle: !!labelLayout.inside }, { textAlign: labelLayout.textAlign, textVerticalAlign: labelLayout.verticalAlign, opacity: data.getItemVisual(idx, 'opacity') } ); labelText.ignore = labelText.normalIgnore = !labelModel.get('show'); labelText.hoverIgnore = !labelHoverModel.get('show'); labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show'); labelLine.hoverIgnore = !labelLineHoverModel.get('show'); // Default use item visual color labelLine.setStyle({ stroke: visualColor, opacity: data.getItemVisual(idx, 'opacity') }); labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle()); labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle(); var smooth = labelLineModel.get('smooth'); if (smooth && smooth === true) { smooth = 0.4; } labelLine.setShape({ smooth: smooth }); }; inherits(PiePiece, Group); // Pie view var PieView = Chart.extend({ type: 'pie', init: function () { var sectorGroup = new Group(); this._sectorGroup = sectorGroup; }, render: function (seriesModel, ecModel, api, payload) { if (payload && (payload.from === this.uid)) { return; } var data = seriesModel.getData(); var oldData = this._data; var group = this.group; var hasAnimation = ecModel.get('animation'); var isFirstRender = !oldData; var animationType = seriesModel.get('animationType'); var onSectorClick = curry( updateDataSelected, this.uid, seriesModel, hasAnimation, api ); var selectedMode = seriesModel.get('selectedMode'); data.diff(oldData) .add(function (idx) { var piePiece = new PiePiece(data, idx); // Default expansion animation if (isFirstRender && animationType !== 'scale') { piePiece.eachChild(function (child) { child.stopAnimation(true); }); } selectedMode && piePiece.on('click', onSectorClick); data.setItemGraphicEl(idx, piePiece); group.add(piePiece); }) .update(function (newIdx, oldIdx) { var piePiece = oldData.getItemGraphicEl(oldIdx); piePiece.updateData(data, newIdx); piePiece.off('click'); selectedMode && piePiece.on('click', onSectorClick); group.add(piePiece); data.setItemGraphicEl(newIdx, piePiece); }) .remove(function (idx) { var piePiece = oldData.getItemGraphicEl(idx); group.remove(piePiece); }) .execute(); if ( hasAnimation && isFirstRender && data.count() > 0 // Default expansion animation && animationType !== 'scale' ) { var shape = data.getItemLayout(0); var r = Math.max(api.getWidth(), api.getHeight()) / 2; var removeClipPath = bind(group.removeClipPath, group); group.setClipPath(this._createClipPath( shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel )); } this._data = data; }, dispose: function () {}, _createClipPath: function ( cx, cy, r, startAngle, clockwise, cb, seriesModel ) { var clipPath = new Sector({ shape: { cx: cx, cy: cy, r0: 0, r: r, startAngle: startAngle, endAngle: startAngle, clockwise: clockwise } }); initProps(clipPath, { shape: { endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2 } }, seriesModel, cb); return clipPath; }, /** * @implement */ containPoint: function (point, seriesModel) { var data = seriesModel.getData(); var itemLayout = data.getItemLayout(0); if (itemLayout) { var dx = point[0] - itemLayout.cx; var dy = point[1] - itemLayout.cy; var radius = Math.sqrt(dx * dx + dy * dy); return radius <= itemLayout.r && radius >= itemLayout.r0; } } }); var createDataSelectAction = function (seriesType, actionInfos) { each$1(actionInfos, function (actionInfo) { actionInfo.update = 'updateView'; /** * @payload * @property {string} seriesName * @property {string} name */ registerAction(actionInfo, function (payload, ecModel) { var selected = {}; ecModel.eachComponent( {mainType: 'series', subType: seriesType, query: payload}, function (seriesModel) { if (seriesModel[actionInfo.method]) { seriesModel[actionInfo.method]( payload.name, payload.dataIndex ); } var data = seriesModel.getData(); // Create selected map data.each(function (idx) { var name = data.getName(idx); selected[name] = seriesModel.isSelected(name) || false; }); } ); return { name: payload.name, selected: selected }; }); }); }; // Pick color from palette for each data item. // Applicable for charts that require applying color palette // in data level (like pie, funnel, chord). var dataColor = function (seriesType) { return { getTargetSeries: function (ecModel) { // Pie and funnel may use diferrent scope var paletteScope = {}; var seiresModelMap = createHashMap(); ecModel.eachSeriesByType(seriesType, function (seriesModel) { seriesModel.__paletteScope = paletteScope; seiresModelMap.set(seriesModel.uid, seriesModel); }); return seiresModelMap; }, reset: function (seriesModel, ecModel) { var dataAll = seriesModel.getRawData(); var idxMap = {}; var data = seriesModel.getData(); data.each(function (idx) { var rawIdx = data.getRawIndex(idx); idxMap[rawIdx] = idx; }); dataAll.each(function (rawIdx) { var filteredIdx = idxMap[rawIdx]; // If series.itemStyle.normal.color is a function. itemVisual may be encoded var singleDataColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'color', true); if (!singleDataColor) { // FIXME Performance var itemModel = dataAll.getItemModel(rawIdx); var color = itemModel.get('itemStyle.color') || seriesModel.getColorFromPalette( dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope, dataAll.count() ); // Legend may use the visual info in data before processed dataAll.setItemVisual(rawIdx, 'color', color); // Data is not filtered if (filteredIdx != null) { data.setItemVisual(filteredIdx, 'color', color); } } else { // Set data all color for legend dataAll.setItemVisual(rawIdx, 'color', singleDataColor); } }); } }; }; // FIXME emphasis label position is not same with normal label position function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) { list.sort(function (a, b) { return a.y - b.y; }); // 压 function shiftDown(start, end, delta, dir) { for (var j = start; j < end; j++) { list[j].y += delta; if (j > start && j + 1 < end && list[j + 1].y > list[j].y + list[j].height ) { shiftUp(j, delta / 2); return; } } shiftUp(end - 1, delta / 2); } // 弹 function shiftUp(end, delta) { for (var j = end; j >= 0; j--) { list[j].y -= delta; if (j > 0 && list[j].y > list[j - 1].y + list[j - 1].height ) { break; } } } function changeX(list, isDownList, cx, cy, r, dir) { var lastDeltaX = dir > 0 ? isDownList // 右侧 ? Number.MAX_VALUE // 下 : 0 // 上 : isDownList // 左侧 ? Number.MAX_VALUE // 下 : 0; // 上 for (var i = 0, l = list.length; i < l; i++) { // Not change x for center label if (list[i].position === 'center') { continue; } var deltaY = Math.abs(list[i].y - cy); var length = list[i].len; var length2 = list[i].len2; var deltaX = (deltaY < r + length) ? Math.sqrt( (r + length + length2) * (r + length + length2) - deltaY * deltaY ) : Math.abs(list[i].x - cx); if (isDownList && deltaX >= lastDeltaX) { // 右下,左下 deltaX = lastDeltaX - 10; } if (!isDownList && deltaX <= lastDeltaX) { // 右上,左上 deltaX = lastDeltaX + 10; } list[i].x = cx + deltaX * dir; lastDeltaX = deltaX; } } var lastY = 0; var delta; var len = list.length; var upList = []; var downList = []; for (var i = 0; i < len; i++) { delta = list[i].y - lastY; if (delta < 0) { shiftDown(i, len, -delta, dir); } lastY = list[i].y + list[i].height; } if (viewHeight - lastY < 0) { shiftUp(len - 1, lastY - viewHeight); } for (var i = 0; i < len; i++) { if (list[i].y >= cy) { downList.push(list[i]); } else { upList.push(list[i]); } } changeX(upList, false, cx, cy, r, dir); changeX(downList, true, cx, cy, r, dir); } function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) { var leftList = []; var rightList = []; for (var i = 0; i < labelLayoutList.length; i++) { if (labelLayoutList[i].x < cx) { leftList.push(labelLayoutList[i]); } else { rightList.push(labelLayoutList[i]); } } adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight); adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight); for (var i = 0; i < labelLayoutList.length; i++) { var linePoints = labelLayoutList[i].linePoints; if (linePoints) { var dist = linePoints[1][0] - linePoints[2][0]; if (labelLayoutList[i].x < cx) { linePoints[2][0] = labelLayoutList[i].x + 3; } else { linePoints[2][0] = labelLayoutList[i].x - 3; } linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y; linePoints[1][0] = linePoints[2][0] + dist; } } } var labelLayout = function (seriesModel, r, viewWidth, viewHeight) { var data = seriesModel.getData(); var labelLayoutList = []; var cx; var cy; var hasLabelRotate = false; data.each(function (idx) { var layout = data.getItemLayout(idx); var itemModel = data.getItemModel(idx); var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position'); var labelLineModel = itemModel.getModel('labelLine'); var labelLineLen = labelLineModel.get('length'); var labelLineLen2 = labelLineModel.get('length2'); var midAngle = (layout.startAngle + layout.endAngle) / 2; var dx = Math.cos(midAngle); var dy = Math.sin(midAngle); var textX; var textY; var linePoints; var textAlign; cx = layout.cx; cy = layout.cy; var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner'; if (labelPosition === 'center') { textX = layout.cx; textY = layout.cy; textAlign = 'center'; } else { var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx; var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy; textX = x1 + dx * 3; textY = y1 + dy * 3; if (!isLabelInside) { // For roseType var x2 = x1 + dx * (labelLineLen + r - layout.r); var y2 = y1 + dy * (labelLineLen + r - layout.r); var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2); var y3 = y2; textX = x3 + (dx < 0 ? -5 : 5); textY = y3; linePoints = [[x1, y1], [x2, y2], [x3, y3]]; } textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right'); } var font = labelModel.getFont(); var labelRotate = labelModel.get('rotate') ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0; var text = seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx); var textRect = getBoundingRect( text, font, textAlign, 'top' ); hasLabelRotate = !!labelRotate; layout.label = { x: textX, y: textY, position: labelPosition, height: textRect.height, len: labelLineLen, len2: labelLineLen2, linePoints: linePoints, textAlign: textAlign, verticalAlign: 'middle', rotation: labelRotate, inside: isLabelInside }; // Not layout the inside label if (!isLabelInside) { labelLayoutList.push(layout.label); } }); if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) { avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight); } }; var PI2$4 = Math.PI * 2; var RADIAN = Math.PI / 180; var pieLayout = function (seriesType, ecModel, api, payload) { ecModel.eachSeriesByType(seriesType, function (seriesModel) { var data = seriesModel.getData(); var valueDim = data.mapDimension('value'); var center = seriesModel.get('center'); var radius = seriesModel.get('radius'); if (!isArray(radius)) { radius = [0, radius]; } if (!isArray(center)) { center = [center, center]; } var width = api.getWidth(); var height = api.getHeight(); var size = Math.min(width, height); var cx = parsePercent$1(center[0], width); var cy = parsePercent$1(center[1], height); var r0 = parsePercent$1(radius[0], size / 2); var r = parsePercent$1(radius[1], size / 2); var startAngle = -seriesModel.get('startAngle') * RADIAN; var minAngle = seriesModel.get('minAngle') * RADIAN; var validDataCount = 0; data.each(valueDim, function (value) { !isNaN(value) && validDataCount++; }); var sum = data.getSum(valueDim); // Sum may be 0 var unitRadian = Math.PI / (sum || validDataCount) * 2; var clockwise = seriesModel.get('clockwise'); var roseType = seriesModel.get('roseType'); var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max] var extent = data.getDataExtent(valueDim); extent[0] = 0; // In the case some sector angle is smaller than minAngle var restAngle = PI2$4; var valueSumLargerThanMinAngle = 0; var currentAngle = startAngle; var dir = clockwise ? 1 : -1; data.each(valueDim, function (value, idx) { var angle; if (isNaN(value)) { data.setItemLayout(idx, { angle: NaN, startAngle: NaN, endAngle: NaN, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? NaN : r }); return; } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样? if (roseType !== 'area') { angle = (sum === 0 && stillShowZeroSum) ? unitRadian : (value * unitRadian); } else { angle = PI2$4 / validDataCount; } if (angle < minAngle) { angle = minAngle; restAngle -= minAngle; } else { valueSumLargerThanMinAngle += value; } var endAngle = currentAngle + dir * angle; data.setItemLayout(idx, { angle: angle, startAngle: currentAngle, endAngle: endAngle, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? linearMap(value, extent, [r0, r]) : r }); currentAngle = endAngle; }); // Some sector is constrained by minAngle // Rest sectors needs recalculate angle if (restAngle < PI2$4 && validDataCount) { // Average the angle if rest angle is not enough after all angles is // Constrained by minAngle if (restAngle <= 1e-3) { var angle = PI2$4 / validDataCount; data.each(valueDim, function (value, idx) { if (!isNaN(value)) { var layout = data.getItemLayout(idx); layout.angle = angle; layout.startAngle = startAngle + dir * idx * angle; layout.endAngle = startAngle + dir * (idx + 1) * angle; } }); } else { unitRadian = restAngle / valueSumLargerThanMinAngle; currentAngle = startAngle; data.each(valueDim, function (value, idx) { if (!isNaN(value)) { var layout = data.getItemLayout(idx); var angle = layout.angle === minAngle ? minAngle : value * unitRadian; layout.startAngle = currentAngle; layout.endAngle = currentAngle + dir * angle; currentAngle += dir * angle; } }); } } labelLayout(seriesModel, r, width, height); }); }; var dataFilter = function (seriesType) { return { seriesType: seriesType, reset: function (seriesModel, ecModel) { var legendModels = ecModel.findComponents({ mainType: 'legend' }); if (!legendModels || !legendModels.length) { return; } var data = seriesModel.getData(); data.filterSelf(function (idx) { var name = data.getName(idx); // If in any legend component the status is not selected. for (var i = 0; i < legendModels.length; i++) { if (!legendModels[i].isSelected(name)) { return false; } } return true; }); } }; }; createDataSelectAction('pie', [{ type: 'pieToggleSelect', event: 'pieselectchanged', method: 'toggleSelected' }, { type: 'pieSelect', event: 'pieselected', method: 'select' }, { type: 'pieUnSelect', event: 'pieunselected', method: 'unSelect' }]); registerVisual(dataColor('pie')); registerLayout(curry(pieLayout, 'pie')); registerProcessor(dataFilter('pie')); exports.version = version; exports.dependencies = dependencies; exports.PRIORITY = PRIORITY; exports.init = init; exports.connect = connect; exports.disConnect = disConnect; exports.disconnect = disconnect; exports.dispose = dispose; exports.getInstanceByDom = getInstanceByDom; exports.getInstanceById = getInstanceById; exports.registerTheme = registerTheme; exports.registerPreprocessor = registerPreprocessor; exports.registerProcessor = registerProcessor; exports.registerPostUpdate = registerPostUpdate; exports.registerAction = registerAction; exports.registerCoordinateSystem = registerCoordinateSystem; exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions; exports.registerLayout = registerLayout; exports.registerVisual = registerVisual; exports.registerLoading = registerLoading; exports.extendComponentModel = extendComponentModel; exports.extendComponentView = extendComponentView; exports.extendSeriesModel = extendSeriesModel; exports.extendChartView = extendChartView; exports.setCanvasCreator = setCanvasCreator; exports.registerMap = registerMap; exports.getMap = getMap; exports.dataTool = dataTool; }))); adminSystem - Gogs: Go Git Service

Brak opisu

dh.js 3.8KB

    var BN = require('bn.js'); var MillerRabin = require('miller-rabin'); var millerRabin = new MillerRabin(); var TWENTYFOUR = new BN(24); var ELEVEN = new BN(11); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var primes = require('./generatePrime'); var randomBytes = require('randombytes'); module.exports = DH; function setPublicKey(pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this._pub = new BN(pub); return this; } function setPrivateKey(priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } this._priv = new BN(priv); return this; } var primeCache = {}; function checkPrime(prime, generator) { var gen = generator.toString('hex'); var hex = [gen, prime.toString(16)].join('_'); if (hex in primeCache) { return primeCache[hex]; } var error = 0; if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { //not a prime so +1 error += 1; if (gen === '02' || gen === '05') { // we'd be able to check the generator // it would fail so +8 error += 8; } else { //we wouldn't be able to test the generator // so +4 error += 4; } primeCache[hex] = error; return error; } if (!millerRabin.test(prime.shrn(1))) { //not a safe prime error += 2; } var rem; switch (gen) { case '02': if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { // unsuidable generator error += 8; } break; case '05': rem = prime.mod(TEN); if (rem.cmp(THREE) && rem.cmp(SEVEN)) { // prime mod 10 needs to equal 3 or 7 error += 8; } break; default: error += 4; } primeCache[hex] = error; return error; } function DH(prime, generator, malleable) { this.setGenerator(generator); this.__prime = new BN(prime); this._prime = BN.mont(this.__prime); this._primeLen = prime.length; this._pub = undefined; this._priv = undefined; this._primeCode = undefined; if (malleable) { this.setPublicKey = setPublicKey; this.setPrivateKey = setPrivateKey; } else { this._primeCode = 8; } } Object.defineProperty(DH.prototype, 'verifyError', { enumerable: true, get: function () { if (typeof this._primeCode !== 'number') { this._primeCode = checkPrime(this.__prime, this.__gen); } return this._primeCode; } }); DH.prototype.generateKeys = function () { if (!this._priv) { this._priv = new BN(randomBytes(this._primeLen)); } this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); return this.getPublicKey(); }; DH.prototype.computeSecret = function (other) { other = new BN(other); other = other.toRed(this._prime); var secret = other.redPow(this._priv).fromRed(); var out = new Buffer(secret.toArray()); var prime = this.getPrime(); if (out.length < prime.length) { var front = new Buffer(prime.length - out.length); front.fill(0); out = Buffer.concat([front, out]); } return out; }; DH.prototype.getPublicKey = function getPublicKey(enc) { return formatReturnValue(this._pub, enc); }; DH.prototype.getPrivateKey = function getPrivateKey(enc) { return formatReturnValue(this._priv, enc); }; DH.prototype.getPrime = function (enc) { return formatReturnValue(this.__prime, enc); }; DH.prototype.getGenerator = function (enc) { return formatReturnValue(this._gen, enc); }; DH.prototype.setGenerator = function (gen, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(gen)) { gen = new Buffer(gen, enc); } this.__gen = gen; this._gen = new BN(gen); return this; }; function formatReturnValue(bn, enc) { var buf = new Buffer(bn.toArray()); if (!enc) { return buf; } else { return buf.toString(enc); } }
adminSystem - Gogs: Go Git Service

Nav apraksta

perf.js 1.4KB

    'use strict'; var oN = require('./O(n)'); var es6Repeat = require('./es6Repeat'); var current = require('../'); var Benchmark = require('benchmark'); var str = "abcd" var len = 100; function buildSuite (note, fns, args) { console.log(note); var suite = new Benchmark.Suite; Object.keys(fns).forEach(function (name) { suite.add(name, function () { fns[name].apply(null, args); }); }); suite.on('cycle', function (event) { console.log(String(event.target)); }).on('complete', function () { console.log('Fastest is ' + this.filter('fastest').map('name')); }); return suite; } var fns = { 'O(n)': oN, 'ES6 Repeat': es6Repeat, 'Current': current }; buildSuite('-> pad 100 spaces to str of len 4', fns, ['abcd', 104, ' ']).run(); buildSuite('-> pad 10 spaces to str of len 4', fns, ['abcd', 14, ' ']).run(); buildSuite('-> pad 9 spaces to str of len 4', fns, ['abcd', 13, ' ']).run(); buildSuite('-> pad 100 to str of len 100', fns, ['0012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123456789', 200, ' ']).run(); buildSuite('-> pad 10 to str of len 100', fns, ['0012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123456789', 110, ' ']).run(); buildSuite('-> pad 9 to str of len 100', fns, ['0012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123456789', 109, ' ']).run();
tonglan/adminSystem - Gogs: Go Git Service

1 次代码提交 (11e3a9652a62b867d722e5aebdba895bb86f9ed3)

作者 SHA1 备注 提交日期
  FFIB 11e3a9652a first 7 年之前