on (item) { var p = coordSys[COORD_CONVERTS[to]](item); xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]); xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]); xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]); xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]); return p; }); return {values: values, xyMinMax: xyMinMax}; } }; function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) { if (__DEV__) { assert$1( coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.' ); } var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]); var values = formatMinMax(map([0, 1], function (i) { return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i])) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i])); })); var xyMinMax = []; xyMinMax[axisNameIndex] = values; xyMinMax[1 - axisNameIndex] = [NaN, NaN]; return {values: values, xyMinMax: xyMinMax}; } var diffProcessor = { lineX: curry$5(axisDiffProcessor, 0), lineY: curry$5(axisDiffProcessor, 1), rect: function (values, refer, scales) { return [ [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]], [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]] ]; }, polygon: function (values, refer, scales) { return map(values, function (item, idx) { return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]]; }); } }; function axisDiffProcessor(axisNameIndex, values, refer, scales) { return [ values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1] ]; } // We have to process scale caused by dataZoom manually, // although it might be not accurate. function getScales(xyMinMaxCurr, xyMinMaxOrigin) { var sizeCurr = getSize(xyMinMaxCurr); var sizeOrigin = getSize(xyMinMaxOrigin); var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]]; isNaN(scales[0]) && (scales[0] = 1); isNaN(scales[1]) && (scales[1] = 1); return scales; } function getSize(xyMinMax) { return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN]; } var STATE_LIST = ['inBrush', 'outOfBrush']; var DISPATCH_METHOD = '__ecBrushSelect'; var DISPATCH_FLAG = '__ecInBrushSelectEvent'; var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH; /** * Layout for visual, the priority higher than other layout, and before brush visual. */ registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) { ecModel.eachComponent({mainType: 'brush'}, function (brushModel) { payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption( payload.key === 'brush' ? payload.brushOption : {brushType: false} ); var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel); brushTargetManager.setInputRanges(brushModel.areas, ecModel); }); }); /** * Register the visual encoding if this modules required. */ registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) { var brushSelected = []; var throttleType; var throttleDelay; ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) { var thisBrushSelected = { brushId: brushModel.id, brushIndex: brushIndex, brushName: brushModel.name, areas: clone(brushModel.areas), selected: [] }; // Every brush component exists in event params, convenient // for user to find by index. brushSelected.push(thisBrushSelected); var brushOption = brushModel.option; var brushLink = brushOption.brushLink; var linkedSeriesMap = []; var selectedDataIndexForLink = []; var rangeInfoBySeries = []; var hasBrushExists = 0; if (!brushIndex) { // Only the first throttle setting works. throttleType = brushOption.throttleType; throttleDelay = brushOption.throttleDelay; } // Add boundingRect and selectors to range. var areas = map(brushModel.areas, function (area) { return bindSelector( defaults( {boundingRect: boundingRectBuilders[area.brushType](area)}, area ) ); }); var visualMappings = createVisualMappings( brushModel.option, STATE_LIST, function (mappingOption) { mappingOption.mappingMethod = 'fixed'; } ); isArray(brushLink) && each$1(brushLink, function (seriesIndex) { linkedSeriesMap[seriesIndex] = 1; }); function linkOthers(seriesIndex) { return brushLink === 'all' || linkedSeriesMap[seriesIndex]; } // If no supported brush or no brush on the series, // all visuals should be in original state. function brushed(rangeInfoList) { return !!rangeInfoList.length; } /** * Logic for each series: (If the logic has to be modified one day, do it carefully!) * * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord. * └!hasBrushExist┘ └nothing. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord. * └!hasBrushExist┘ └nothing. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck. * !brushed┘ └nothing. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing. */ // Step A ecModel.eachSeries(function (seriesModel, seriesIndex) { var rangeInfoList = rangeInfoBySeries[seriesIndex] = []; seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex, rangeInfoList) : stepAOthers(seriesModel, seriesIndex, rangeInfoList); }); function stepAParallel(seriesModel, seriesIndex) { var coordSys = seriesModel.coordinateSystem; hasBrushExists |= coordSys.hasAxisBrushed(); linkOthers(seriesIndex) && coordSys.eachActiveState( seriesModel.getData(), function (activeState, dataIndex) { activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1); } ); } function stepAOthers(seriesModel, seriesIndex, rangeInfoList) { var selectorsByBrushType = getSelectorsByBrushType(seriesModel); if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) { return; } each$1(areas, function (area) { selectorsByBrushType[area.brushType] && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel) && rangeInfoList.push(area); hasBrushExists |= brushed(rangeInfoList); }); if (linkOthers(seriesIndex) && brushed(rangeInfoList)) { var data = seriesModel.getData(); data.each(function (dataIndex) { if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) { selectedDataIndexForLink[dataIndex] = 1; } }); } } // Step B ecModel.eachSeries(function (seriesModel, seriesIndex) { var seriesBrushSelected = { seriesId: seriesModel.id, seriesIndex: seriesIndex, seriesName: seriesModel.name, dataIndex: [] }; // Every series exists in event params, convenient // for user to find series by seriesIndex. thisBrushSelected.selected.push(seriesBrushSelected); var selectorsByBrushType = getSelectorsByBrushType(seriesModel); var rangeInfoList = rangeInfoBySeries[seriesIndex]; var data = seriesModel.getData(); var getValueState = linkOthers(seriesIndex) ? function (dataIndex) { return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush'; } : function (dataIndex) { return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush'; }; // If no supported brush or no brush, all visuals are in original state. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual( STATE_LIST, visualMappings, data, getValueState ); }); }); dispatchAction(api, throttleType, throttleDelay, brushSelected, payload); }); function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) { // This event will not be triggered when `setOpion`, otherwise dead lock may // triggered when do `setOption` in event listener, which we do not find // satisfactory way to solve yet. Some considered resolutions: // (a) Diff with prevoius selected data ant only trigger event when changed. // But store previous data and diff precisely (i.e., not only by dataIndex, but // also detect value changes in selected data) might bring complexity or fragility. // (b) Use spectial param like `silent` to suppress event triggering. // But such kind of volatile param may be weird in `setOption`. if (!payload) { return; } var zr = api.getZr(); if (zr[DISPATCH_FLAG]) { return; } if (!zr[DISPATCH_METHOD]) { zr[DISPATCH_METHOD] = doDispatch; } var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType); fn(api, brushSelected); } function doDispatch(api, brushSelected) { if (!api.isDisposed()) { var zr = api.getZr(); zr[DISPATCH_FLAG] = true; api.dispatchAction({ type: 'brushSelect', batch: brushSelected }); zr[DISPATCH_FLAG] = false; } } function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) { for (var i = 0, len = rangeInfoList.length; i < len; i++) { var area = rangeInfoList[i]; if (selectorsByBrushType[area.brushType]( dataIndex, data, area.selectors, area )) { return true; } } } function getSelectorsByBrushType(seriesModel) { var brushSelector = seriesModel.brushSelector; if (isString(brushSelector)) { var sels = []; each$1(selector, function (selectorsByElementType, brushType) { sels[brushType] = function (dataIndex, data, selectors, area) { var itemLayout = data.getItemLayout(dataIndex); return selectorsByElementType[brushSelector](itemLayout, selectors, area); }; }); return sels; } else if (isFunction$1(brushSelector)) { var bSelector = {}; each$1(selector, function (sel, brushType) { bSelector[brushType] = brushSelector; }); return bSelector; } return brushSelector; } function brushModelNotControll(brushModel, seriesIndex) { var seriesIndices = brushModel.option.seriesIndex; return seriesIndices != null && seriesIndices !== 'all' && ( isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices ); } function bindSelector(area) { var selectors = area.selectors = {}; each$1(selector[area.brushType], function (selFn, elType) { // Do not use function binding or curry for performance. selectors[elType] = function (itemLayout) { return selFn(itemLayout, selectors, area); }; }); return area; } var boundingRectBuilders = { lineX: noop, lineY: noop, rect: function (area) { return getBoundingRectFromMinMax(area.range); }, polygon: function (area) { var minMax; var range = area.range; for (var i = 0, len = range.length; i < len; i++) { minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]]; var rg = range[i]; rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]); rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]); rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]); rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]); } return minMax && getBoundingRectFromMinMax(minMax); } }; function getBoundingRectFromMinMax(minMax) { return new BoundingRect( minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0] ); } var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd']; var BrushModel = extendComponentModel({ type: 'brush', dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'], /** * @protected */ defaultOption: { // inBrush: null, // outOfBrush: null, toolbox: null, // Default value see preprocessor. brushLink: null, // Series indices array, broadcast using dataIndex. // or 'all', which means all series. 'none' or null means no series. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component. geoIndex: null, // xAxisIndex: null, yAxisIndex: null, brushType: 'rect', // Default brushType, see BrushController. brushMode: 'single', // Default brushMode, 'single' or 'multiple' transformable: true, // Default transformable. brushStyle: { // Default brushStyle borderWidth: 1, color: 'rgba(120,140,180,0.3)', borderColor: 'rgba(120,140,180,0.8)' }, throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'. // If null, no throttle. Valid only in the first brush component throttleDelay: 0, // Unit: ms, 0 means every event will be triggered. // FIXME // 试验效果 removeOnClick: true, z: 10000 }, /** * @readOnly * @type {Array.<Object>} */ areas: [], /** * Current activated brush type. * If null, brush is inactived. * see module:echarts/component/helper/BrushController * @readOnly * @type {string} */ brushType: null, /** * Current brush opt. * see module:echarts/component/helper/BrushController * @readOnly * @type {Object} */ brushOption: {}, /** * @readOnly * @type {Array.<Object>} */ coordInfoList: [], optionUpdated: function (newOption, isInit) { var thisOption = this.option; !isInit && replaceVisualOption( thisOption, newOption, ['inBrush', 'outOfBrush'] ); thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR}; }, /** * If ranges is null/undefined, range state remain. * * @param {Array.<Object>} [ranges] */ setAreas: function (areas) { if (__DEV__) { assert$1(isArray(areas)); each$1(areas, function (area) { assert$1(area.brushType, 'Illegal areas'); }); } // If ranges is null/undefined, range state remain. // This helps user to dispatchAction({type: 'brush'}) with no areas // set but just want to get the current brush select info from a `brush` event. if (!areas) { return; } this.areas = map(areas, function (area) { return generateBrushOption(this.option, area); }, this); }, /** * see module:echarts/component/helper/BrushController * @param {Object} brushOption */ setBrushOption: function (brushOption) { this.brushOption = generateBrushOption(this.option, brushOption); this.brushType = this.brushOption.brushType; } }); function generateBrushOption(option, brushOption) { return merge( { brushType: option.brushType, brushMode: option.brushMode, transformable: option.transformable, brushStyle: new Model(option.brushStyle).getItemStyle(), removeOnClick: option.removeOnClick, z: option.z }, brushOption, true ); } extendComponentView({ type: 'brush', init: function (ecModel, api) { /** * @readOnly * @type {module:echarts/model/Global} */ this.ecModel = ecModel; /** * @readOnly * @type {module:echarts/ExtensionAPI} */ this.api = api; /** * @readOnly * @type {module:echarts/component/brush/BrushModel} */ this.model; /** * @private * @type {module:echarts/component/helper/BrushController} */ (this._brushController = new BrushController(api.getZr())) .on('brush', bind(this._onBrush, this)) .mount(); }, /** * @override */ render: function (brushModel) { this.model = brushModel; return updateController.apply(this, arguments); }, /** * @override */ updateTransform: updateController, /** * @override */ updateView: updateController, // /** // * @override // */ // updateLayout: updateController, // /** // * @override // */ // updateVisual: updateController, /** * @override */ dispose: function () { this._brushController.dispose(); }, /** * @private */ _onBrush: function (areas, opt) { var modelId = this.model.id; this.model.brushTargetManager.setOutputRanges(areas, this.ecModel); // Action is not dispatched on drag end, because the drag end // emits the same params with the last drag move event, and // may have some delay when using touch pad, which makes // animation not smooth (when using debounce). (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({ type: 'brush', brushId: modelId, areas: clone(areas), $from: modelId }); } }); function updateController(brushModel, ecModel, api, payload) { // Do not update controller when drawing. (!payload || payload.$from !== brushModel.id) && this._brushController .setPanels(brushModel.brushTargetManager.makePanelOpts(api)) .enableBrush(brushModel.brushOption) .updateCovers(brushModel.areas.slice()); } /** * payload: { * brushIndex: number, or, * brushId: string, or, * brushName: string, * globalRanges: Array * } */ registerAction( {type: 'brush', event: 'brush' /*, update: 'updateView' */}, function (payload, ecModel) { ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) { brushModel.setAreas(payload.areas); }); } ); /** * payload: { * brushComponents: [ * { * brushId, * brushIndex, * brushName, * series: [ * { * seriesId, * seriesIndex, * seriesName, * rawIndices: [21, 34, ...] * }, * ... * ] * }, * ... * ] * } */ registerAction( {type: 'brushSelect', event: 'brushSelected', update: 'none'}, function () {} ); var features = {}; function register$1(name, ctor) { features[name] = ctor; } function get$1(name) { return features[name]; } var brushLang = lang.toolbox.brush; function Brush(model, ecModel, api) { this.model = model; this.ecModel = ecModel; this.api = api; /** * @private * @type {string} */ this._brushType; /** * @private * @type {string} */ this._brushMode; } Brush.defaultOption = { show: true, type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'], icon: { rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13', // jshint ignore:line polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2', // jshint ignore:line lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4', // jshint ignore:line lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4', // jshint ignore:line keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z', // jshint ignore:line clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' // jshint ignore:line }, // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear` title: clone(brushLang.title) }; var proto$3 = Brush.prototype; // proto.updateLayout = function (featureModel, ecModel, api) { proto$3.render = proto$3.updateView = function (featureModel, ecModel, api) { var brushType; var brushMode; var isBrushed; ecModel.eachComponent({mainType: 'brush'}, function (brushModel) { brushType = brushModel.brushType; brushMode = brushModel.brushOption.brushMode || 'single'; isBrushed |= brushModel.areas.length; }); this._brushType = brushType; this._brushMode = brushMode; each$1(featureModel.get('type', true), function (type) { featureModel.setIconStatus( type, ( type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType ) ? 'emphasis' : 'normal' ); }); }; proto$3.getIcons = function () { var model = this.model; var availableIcons = model.get('icon', true); var icons = {}; each$1(model.get('type', true), function (type) { if (availableIcons[type]) { icons[type] = availableIcons[type]; } }); return icons; }; proto$3.onclick = function (ecModel, api, type) { var brushType = this._brushType; var brushMode = this._brushMode; if (type === 'clear') { // Trigger parallel action firstly api.dispatchAction({ type: 'axisAreaSelect', intervals: [] }); api.dispatchAction({ type: 'brush', command: 'clear', // Clear all areas of all brush components. areas: [] }); } else { api.dispatchAction({ type: 'takeGlobalCursor', key: 'brush', brushOption: { brushType: type === 'keep' ? brushType : (brushType === type ? false : type), brushMode: type === 'keep' ? (brushMode === 'multiple' ? 'single' : 'multiple') : brushMode } }); } }; register$1('brush', Brush); /** * Brush component entry */ registerPreprocessor(preprocessor$1); // (24*60*60*1000) var PROXIMATE_ONE_DAY = 86400000; /** * Calendar * * @constructor * * @param {Object} calendarModel calendarModel * @param {Object} ecModel ecModel * @param {Object} api api */ function Calendar(calendarModel, ecModel, api) { this._model = calendarModel; } Calendar.prototype = { constructor: Calendar, type: 'calendar', dimensions: ['time', 'value'], // Required in createListFromData getDimensionsInfo: function () { return [{name: 'time', type: 'time'}, 'value']; }, getRangeInfo: function () { return this._rangeInfo; }, getModel: function () { return this._model; }, getRect: function () { return this._rect; }, getCellWidth: function () { return this._sw; }, getCellHeight: function () { return this._sh; }, getOrient: function () { return this._orient; }, /** * getFirstDayOfWeek * * @example * 0 : start at Sunday * 1 : start at Monday * * @return {number} */ getFirstDayOfWeek: function () { return this._firstDayOfWeek; }, /** * get date info * * @param {string|number} date date * @return {Object} * { * y: string, local full year, eg., '1940', * m: string, local month, from '01' ot '12', * d: string, local date, from '01' to '31' (if exists), * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6, * time: timestamp, * formatedDate: string, yyyy-MM-dd, * date: original date object. * } */ getDateInfo: function (date) { date = parseDate(date); var y = date.getFullYear(); var m = date.getMonth() + 1; m = m < 10 ? '0' + m : m; var d = date.getDate(); d = d < 10 ? '0' + d : d; var day = date.getDay(); day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7); return { y: y, m: m, d: d, day: day, time: date.getTime(), formatedDate: y + '-' + m + '-' + d, date: date }; }, getNextNDay: function (date, n) { n = n || 0; if (n === 0) { return this.getDateInfo(date); } date = new Date(this.getDateInfo(date).time); date.setDate(date.getDate() + n); return this.getDateInfo(date); }, update: function (ecModel, api) { this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay'); this._orient = this._model.get('orient'); this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0; this._rangeInfo = this._getRangeInfo(this._initRangeOption()); var weeks = this._rangeInfo.weeks || 1; var whNames = ['width', 'height']; var cellSize = this._model.get('cellSize').slice(); var layoutParams = this._model.getBoxLayoutParams(); var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks]; each$1([0, 1], function (idx) { if (cellSizeSpecified(cellSize, idx)) { layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx]; } }); var whGlobal = { width: api.getWidth(), height: api.getHeight() }; var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal); each$1([0, 1], function (idx) { if (!cellSizeSpecified(cellSize, idx)) { cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx]; } }); function cellSizeSpecified(cellSize, idx) { return cellSize[idx] != null && cellSize[idx] !== 'auto'; } this._sw = cellSize[0]; this._sh = cellSize[1]; }, /** * Convert a time data(time, value) item to (x, y) point. * * @override * @param {Array|number} data data * @param {boolean} [clamp=true] out of range * @return {Array} point */ dataToPoint: function (data, clamp) { isArray(data) && (data = data[0]); clamp == null && (clamp = true); var dayInfo = this.getDateInfo(data); var range = this._rangeInfo; var date = dayInfo.formatedDate; // if not in range return [NaN, NaN] if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) { return [NaN, NaN]; } var week = dayInfo.day; var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek; if (this._orient === 'vertical') { return [ this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2 ]; } return [ this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2 ]; }, /** * Convert a (x, y) point to time data * * @override * @param {string} point point * @return {string} data */ pointToData: function (point) { var date = this.pointToDate(point); return date && date.time; }, /** * Convert a time date item to (x, y) four point. * * @param {Array} data date[0] is date * @param {boolean} [clamp=true] out of range * @return {Object} point */ dataToRect: function (data, clamp) { var point = this.dataToPoint(data, clamp); return { contentShape: { x: point[0] - (this._sw - this._lineWidth) / 2, y: point[1] - (this._sh - this._lineWidth) / 2, width: this._sw - this._lineWidth, height: this._sh - this._lineWidth }, center: point, tl: [ point[0] - this._sw / 2, point[1] - this._sh / 2 ], tr: [ point[0] + this._sw / 2, point[1] - this._sh / 2 ], br: [ point[0] + this._sw / 2, point[1] + this._sh / 2 ], bl: [ point[0] - this._sw / 2, point[1] + this._sh / 2 ] }; }, /** * Convert a (x, y) point to time date * * @param {Array} point point * @return {Object} date */ pointToDate: function (point) { var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1; var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1; var range = this._rangeInfo.range; if (this._orient === 'vertical') { return this._getDateByWeeksAndDay(nthY, nthX - 1, range); } return this._getDateByWeeksAndDay(nthX, nthY - 1, range); }, /** * @inheritDoc */ convertToPixel: curry(doConvert$2, 'dataToPoint'), /** * @inheritDoc */ convertFromPixel: curry(doConvert$2, 'pointToData'), /** * initRange * * @private * @return {Array} [start, end] */ _initRangeOption: function () { var range = this._model.get('range'); var rg = range; if (isArray(rg) && rg.length === 1) { rg = rg[0]; } if (/^\d{4}$/.test(rg)) { range = [rg + '-01-01', rg + '-12-31']; } if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) { var start = this.getDateInfo(rg); var firstDay = start.date; firstDay.setMonth(firstDay.getMonth() + 1); var end = this.getNextNDay(firstDay, -1); range = [start.formatedDate, end.formatedDate]; } if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) { range = [rg, rg]; } var tmp = this._getRangeInfo(range); if (tmp.start.time > tmp.end.time) { range.reverse(); } return range; }, /** * range info * * @private * @param {Array} range range ['2017-01-01', '2017-07-08'] * If range[0] > range[1], they will not be reversed. * @return {Object} obj */ _getRangeInfo: function (range) { range = [ this.getDateInfo(range[0]), this.getDateInfo(range[1]) ]; var reversed; if (range[0].time > range[1].time) { reversed = true; range.reverse(); } var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY) - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case: // Firstly set system timezone as "Time Zone: America/Toronto", // ``` // var first = new Date(1478412000000 - 3600 * 1000 * 2.5); // var second = new Date(1478412000000); // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1; // ``` // will get wrong result because of DST. So we should fix it. var date = new Date(range[0].time); var startDateNum = date.getDate(); var endDateNum = range[1].date.getDate(); date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date. if (date.getDate() !== endDateNum) { var sign = date.getTime() - range[1].time > 0 ? 1 : -1; while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) { allDay -= sign; date.setDate(startDateNum + allDay - 1); } } var weeks = Math.floor((allDay + range[0].day + 6) / 7); var nthWeek = reversed ? -weeks + 1: weeks - 1; reversed && range.reverse(); return { range: [range[0].formatedDate, range[1].formatedDate], start: range[0], end: range[1], allDay: allDay, weeks: weeks, // From 0. nthWeek: nthWeek, fweek: range[0].day, lweek: range[1].day }; }, /** * get date by nthWeeks and week day in range * * @private * @param {number} nthWeek the week * @param {number} day the week day * @param {Array} range [d1, d2] * @return {Object} */ _getDateByWeeksAndDay: function (nthWeek, day, range) { var rangeInfo = this._getRangeInfo(range); if (nthWeek > rangeInfo.weeks || (nthWeek === 0 && day < rangeInfo.fweek) || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) ) { return false; } var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day; var date = new Date(rangeInfo.start.time); date.setDate(rangeInfo.start.d + nthDay); return this.getDateInfo(date); } }; Calendar.dimensions = Calendar.prototype.dimensions; Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo; Calendar.create = function (ecModel, api) { var calendarList = []; ecModel.eachComponent('calendar', function (calendarModel) { var calendar = new Calendar(calendarModel, ecModel, api); calendarList.push(calendar); calendarModel.coordinateSystem = calendar; }); ecModel.eachSeries(function (calendarSeries) { if (calendarSeries.get('coordinateSystem') === 'calendar') { // Inject coordinate system calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0]; } }); return calendarList; }; function doConvert$2(methodName, ecModel, finder, value) { var calendarModel = finder.calendarModel; var seriesModel = finder.seriesModel; var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null; return coordSys === this ? coordSys[methodName](value) : null; } CoordinateSystemManager.register('calendar', Calendar); var CalendarModel = ComponentModel.extend({ type: 'calendar', /** * @type {module:echarts/coord/calendar/Calendar} */ coordinateSystem: null, defaultOption: { zlevel: 0, z: 2, left: 80, top: 60, cellSize: 20, // horizontal vertical orient: 'horizontal', // month separate line style splitLine: { show: true, lineStyle: { color: '#000', width: 1, type: 'solid' } }, // rect style temporarily unused emphasis itemStyle: { color: '#fff', borderWidth: 1, borderColor: '#ccc' }, // week text style dayLabel: { show: true, // a week first day firstDay: 0, // start end position: 'start', margin: '50%', // 50% of cellSize nameMap: 'en', color: '#000' }, // month text style monthLabel: { show: true, // start end position: 'start', margin: 5, // center or left align: 'center', // cn en [] nameMap: 'en', formatter: null, color: '#000' }, // year text style yearLabel: { show: true, // top bottom left right position: null, margin: 30, formatter: null, color: '#ccc', fontFamily: 'sans-serif', fontWeight: 'bolder', fontSize: 20 } }, /** * @override */ init: function (option, parentModel, ecModel, extraOpt) { var inputPositionParams = getLayoutParams(option); CalendarModel.superApply(this, 'init', arguments); mergeAndNormalizeLayoutParams$1(option, inputPositionParams); }, /** * @override */ mergeOption: function (option, extraOpt) { CalendarModel.superApply(this, 'mergeOption', arguments); mergeAndNormalizeLayoutParams$1(this.option, option); } }); function mergeAndNormalizeLayoutParams$1(target, raw) { // Normalize cellSize var cellSize = target.cellSize; if (!isArray(cellSize)) { cellSize = target.cellSize = [cellSize, cellSize]; } else if (cellSize.length === 1) { cellSize[1] = cellSize[0]; } var ignoreSize = map([0, 1], function (hvIdx) { // If user have set `width` or both `left` and `right`, cellSize // will be automatically set to 'auto', otherwise the default // setting of cellSize will make `width` setting not work. if (sizeCalculable(raw, hvIdx)) { cellSize[hvIdx] = 'auto'; } return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto'; }); mergeLayoutParam(target, raw, { type: 'box', ignoreSize: ignoreSize }); } var MONTH_TEXT = { EN: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], CN: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ] }; var WEEK_TEXT = { EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], CN: ['日', '一', '二', '三', '四', '五', '六'] }; extendComponentView({ type: 'calendar', /** * top/left line points * @private */ _tlpoints: null, /** * bottom/right line points * @private */ _blpoints: null, /** * first day of month * @private */ _firstDayOfMonth: null, /** * first day point of month * @private */ _firstDayPoints: null, render: function (calendarModel, ecModel, api) { var group = this.group; group.removeAll(); var coordSys = calendarModel.coordinateSystem; // range info var rangeData = coordSys.getRangeInfo(); var orient = coordSys.getOrient(); this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function this._renderLines(calendarModel, rangeData, orient, group); this._renderYearText(calendarModel, rangeData, orient, group); this._renderMonthText(calendarModel, orient, group); this._renderWeekText(calendarModel, rangeData, orient, group); }, // render day rect _renderDayRect: function (calendarModel, rangeData, group) { var coordSys = calendarModel.coordinateSystem; var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle(); var sw = coordSys.getCellWidth(); var sh = coordSys.getCellHeight(); for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time ) { var point = coordSys.dataToRect([i], false).tl; // every rect var rect = new Rect({ shape: { x: point[0], y: point[1], width: sw, height: sh }, cursor: 'default', style: itemRectStyleModel }); group.add(rect); } }, // render separate line _renderLines: function (calendarModel, rangeData, orient, group) { var self = this; var coordSys = calendarModel.coordinateSystem; var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle(); var show = calendarModel.get('splitLine.show'); var lineWidth = lineStyleModel.lineWidth; this._tlpoints = []; this._blpoints = []; this._firstDayOfMonth = []; this._firstDayPoints = []; var firstDay = rangeData.start; for (var i = 0; firstDay.time <= rangeData.end.time; i++) { addPoints(firstDay.formatedDate); if (i === 0) { firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m); } var date = firstDay.date; date.setMonth(date.getMonth() + 1); firstDay = coordSys.getDateInfo(date); } addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate); function addPoints(date) { self._firstDayOfMonth.push(coordSys.getDateInfo(date)); self._firstDayPoints.push(coordSys.dataToRect([date], false).tl); var points = self._getLinePointsOfOneWeek(calendarModel, date, orient); self._tlpoints.push(points[0]); self._blpoints.push(points[points.length - 1]); show && self._drawSplitline(points, lineStyleModel, group); } // render top/left line show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group); }, // get points at both ends _getEdgesPoints: function (points, lineWidth, orient) { var rs = [points[0].slice(), points[points.length - 1].slice()]; var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth rs[0][idx] = rs[0][idx] - lineWidth / 2; rs[1][idx] = rs[1][idx] + lineWidth / 2; return rs; }, // render split line _drawSplitline: function (points, lineStyleModel, group) { var poyline = new Polyline({ z2: 20, shape: { points: points }, style: lineStyleModel }); group.add(poyline); }, // render month line of one week points _getLinePointsOfOneWeek: function (calendarModel, date, orient) { var coordSys = calendarModel.coordinateSystem; date = coordSys.getDateInfo(date); var points = []; for (var i = 0; i < 7; i++) { var tmpD = coordSys.getNextNDay(date.time, i); var point = coordSys.dataToRect([tmpD.time], false); points[2 * tmpD.day] = point.tl; points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr']; } return points; }, _formatterLabel: function (formatter, params) { if (typeof formatter === 'string' && formatter) { return formatTplSimple(formatter, params); } if (typeof formatter === 'function') { return formatter(params); } return params.nameMap; }, _yearTextPositionControl: function (textEl, point, orient, position, margin) { point = point.slice(); var aligns = ['center', 'bottom']; if (position === 'bottom') { point[1] += margin; aligns = ['center', 'top']; } else if (position === 'left') { point[0] -= margin; } else if (position === 'right') { point[0] += margin; aligns = ['center', 'top']; } else { // top point[1] -= margin; } var rotate = 0; if (position === 'left' || position === 'right') { rotate = Math.PI / 2; } return { rotation: rotate, position: point, style: { textAlign: aligns[0], textVerticalAlign: aligns[1] } }; }, // render year _renderYearText: function (calendarModel, rangeData, orient, group) { var yearLabel = calendarModel.getModel('yearLabel'); if (!yearLabel.get('show')) { return; } var margin = yearLabel.get('margin'); var pos = yearLabel.get('position'); if (!pos) { pos = orient !== 'horizontal' ? 'top' : 'left'; } var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]]; var xc = (points[0][0] + points[1][0]) / 2; var yc = (points[0][1] + points[1][1]) / 2; var idx = orient === 'horizontal' ? 0 : 1; var posPoints = { top: [xc, points[idx][1]], bottom: [xc, points[1 - idx][1]], left: [points[1 - idx][0], yc], right: [points[idx][0], yc] }; var name = rangeData.start.y; if (+rangeData.end.y > +rangeData.start.y) { name = name + '-' + rangeData.end.y; } var formatter = yearLabel.get('formatter'); var params = { start: rangeData.start.y, end: rangeData.end.y, nameMap: name }; var content = this._formatterLabel(formatter, params); var yearText = new Text({z2: 30}); setTextStyle(yearText.style, yearLabel, {text: content}), yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin)); group.add(yearText); }, _monthTextPositionControl: function (point, isCenter, orient, position, margin) { var align = 'left'; var vAlign = 'top'; var x = point[0]; var y = point[1]; if (orient === 'horizontal') { y = y + margin; if (isCenter) { align = 'center'; } if (position === 'start') { vAlign = 'bottom'; } } else { x = x + margin; if (isCenter) { vAlign = 'middle'; } if (position === 'start') { align = 'right'; } } return { x: x, y: y, textAlign: align, textVerticalAlign: vAlign }; }, // render month and year text _renderMonthText: function (calendarModel, orient, group) { var monthLabel = calendarModel.getModel('monthLabel'); if (!monthLabel.get('show')) { return; } var nameMap = monthLabel.get('nameMap'); var margin = monthLabel.get('margin'); var pos = monthLabel.get('position'); var align = monthLabel.get('align'); var termPoints = [this._tlpoints, this._blpoints]; if (isString(nameMap)) { nameMap = MONTH_TEXT[nameMap.toUpperCase()] || []; } var idx = pos === 'start' ? 0 : 1; var axis = orient === 'horizontal' ? 0 : 1; margin = pos === 'start' ? -margin : margin; var isCenter = (align === 'center'); for (var i = 0; i < termPoints[idx].length - 1; i++) { var tmp = termPoints[idx][i].slice(); var firstDay = this._firstDayOfMonth[i]; if (isCenter) { var firstDayPoints = this._firstDayPoints[i]; tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2; } var formatter = monthLabel.get('formatter'); var name = nameMap[+firstDay.m - 1]; var params = { yyyy: firstDay.y, yy: (firstDay.y + '').slice(2), MM: firstDay.m, M: +firstDay.m, nameMap: name }; var content = this._formatterLabel(formatter, params); var monthText = new Text({z2: 30}); extend( setTextStyle(monthText.style, monthLabel, {text: content}), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin) ); group.add(monthText); } }, _weekTextPositionControl: function (point, orient, position, margin, cellSize) { var align = 'center'; var vAlign = 'middle'; var x = point[0]; var y = point[1]; var isStart = position === 'start'; if (orient === 'horizontal') { x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2; align = isStart ? 'right' : 'left'; } else { y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2; vAlign = isStart ? 'bottom' : 'top'; } return { x: x, y: y, textAlign: align, textVerticalAlign: vAlign }; }, // render weeks _renderWeekText: function (calendarModel, rangeData, orient, group) { var dayLabel = calendarModel.getModel('dayLabel'); if (!dayLabel.get('show')) { return; } var coordSys = calendarModel.coordinateSystem; var pos = dayLabel.get('position'); var nameMap = dayLabel.get('nameMap'); var margin = dayLabel.get('margin'); var firstDayOfWeek = coordSys.getFirstDayOfWeek(); if (isString(nameMap)) { nameMap = WEEK_TEXT[nameMap.toUpperCase()] || []; } var start = coordSys.getNextNDay( rangeData.end.time, (7 - rangeData.lweek) ).time; var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()]; margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]); if (pos === 'start') { start = coordSys.getNextNDay( rangeData.start.time, -(7 + rangeData.fweek) ).time; margin = -margin; } for (var i = 0; i < 7; i++) { var tmpD = coordSys.getNextNDay(start, i); var point = coordSys.dataToRect([tmpD.time], false).center; var day = i; day = Math.abs((i + firstDayOfWeek) % 7); var weekText = new Text({z2: 30}); extend( setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}), this._weekTextPositionControl(point, orient, pos, margin, cellSize) ); group.add(weekText); } } }); /** * @file calendar.js * @author dxh */ // Model extendComponentModel({ type: 'title', layoutMode: {type: 'box', ignoreSize: true}, defaultOption: { // 一级层叠 zlevel: 0, // 二级层叠 z: 6, show: true, text: '', // 超链接跳转 // link: null, // 仅支持self | blank target: 'blank', subtext: '', // 超链接跳转 // sublink: null, // 仅支持self | blank subtarget: 'blank', // 'center' ¦ 'left' ¦ 'right' // ¦ {number}(x坐标,单位px) left: 0, // 'top' ¦ 'bottom' ¦ 'center' // ¦ {number}(y坐标,单位px) top: 0, // 水平对齐 // 'auto' | 'left' | 'right' | 'center' // 默认根据 left 的位置判断是左对齐还是右对齐 // textAlign: null // // 垂直对齐 // 'auto' | 'top' | 'bottom' | 'middle' // 默认根据 top 位置判断是上对齐还是下对齐 // textBaseline: null backgroundColor: 'rgba(0,0,0,0)', // 标题边框颜色 borderColor: '#ccc', // 标题边框线宽,单位px,默认为0(无边框) borderWidth: 0, // 标题内边距,单位px,默认各方向内边距为5, // 接受数组分别设定上右下左边距,同css padding: 5, // 主副标题纵向间隔,单位px,默认为10, itemGap: 10, textStyle: { fontSize: 18, fontWeight: 'bolder', color: '#333' }, subtextStyle: { color: '#aaa' } } }); // View extendComponentView({ type: 'title', render: function (titleModel, ecModel, api) { this.group.removeAll(); if (!titleModel.get('show')) { return; } var group = this.group; var textStyleModel = titleModel.getModel('textStyle'); var subtextStyleModel = titleModel.getModel('subtextStyle'); var textAlign = titleModel.get('textAlign'); var textBaseline = titleModel.get('textBaseline'); var textEl = new Text({ style: setTextStyle({}, textStyleModel, { text: titleModel.get('text'), textFill: textStyleModel.getTextColor() }, {disableBox: true}), z2: 10 }); var textRect = textEl.getBoundingRect(); var subText = titleModel.get('subtext'); var subTextEl = new Text({ style: setTextStyle({}, subtextStyleModel, { text: subText, textFill: subtextStyleModel.getTextColor(), y: textRect.height + titleModel.get('itemGap'), textVerticalAlign: 'top' }, {disableBox: true}), z2: 10 }); var link = titleModel.get('link'); var sublink = titleModel.get('sublink'); textEl.silent = !link; subTextEl.silent = !sublink; if (link) { textEl.on('click', function () { window.open(link, '_' + titleModel.get('target')); }); } if (sublink) { subTextEl.on('click', function () { window.open(sublink, '_' + titleModel.get('subtarget')); }); } group.add(textEl); subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line. var groupRect = group.getBoundingRect(); var layoutOption = titleModel.getBoxLayoutParams(); layoutOption.width = groupRect.width; layoutOption.height = groupRect.height; var layoutRect = getLayoutRect( layoutOption, { width: api.getWidth(), height: api.getHeight() }, titleModel.get('padding') ); // Adjust text align based on position if (!textAlign) { // Align left if title is on the left. center and right is same textAlign = titleModel.get('left') || titleModel.get('right'); if (textAlign === 'middle') { textAlign = 'center'; } // Adjust layout by text align if (textAlign === 'right') { layoutRect.x += layoutRect.width; } else if (textAlign === 'center') { layoutRect.x += layoutRect.width / 2; } } if (!textBaseline) { textBaseline = titleModel.get('top') || titleModel.get('bottom'); if (textBaseline === 'center') { textBaseline = 'middle'; } if (textBaseline === 'bottom') { layoutRect.y += layoutRect.height; } else if (textBaseline === 'middle') { layoutRect.y += layoutRect.height / 2; } textBaseline = textBaseline || 'top'; } group.attr('position', [layoutRect.x, layoutRect.y]); var alignStyle = { textAlign: textAlign, textVerticalAlign: textBaseline }; textEl.setStyle(alignStyle); subTextEl.setStyle(alignStyle); // Render background // Get groupRect again because textAlign has been changed groupRect = group.getBoundingRect(); var padding = layoutRect.margin; var style = titleModel.getItemStyle(['color', 'opacity']); style.fill = titleModel.get('backgroundColor'); var rect = new Rect({ shape: { x: groupRect.x - padding[3], y: groupRect.y - padding[0], width: groupRect.width + padding[1] + padding[3], height: groupRect.height + padding[0] + padding[2], r: titleModel.get('borderRadius') }, style: style, silent: true }); subPixelOptimizeRect(rect); group.add(rect); } }); ComponentModel.registerSubTypeDefaulter('dataZoom', function () { // Default 'slider' when no type specified. return 'slider'; }); var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single']; // Supported coords. var COORDS = ['cartesian2d', 'polar', 'singleAxis']; /** * @param {string} coordType * @return {boolean} */ function isCoordSupported(coordType) { return indexOf(COORDS, coordType) >= 0; } /** * Create "each" method to iterate names. * * @pubilc * @param {Array.<string>} names * @param {Array.<string>=} attrs * @return {Function} */ function createNameEach(names, attrs) { names = names.slice(); var capitalNames = map(names, capitalFirst); attrs = (attrs || []).slice(); var capitalAttrs = map(attrs, capitalFirst); return function (callback, context) { each$1(names, function (name, index) { var nameObj = {name: name, capital: capitalNames[index]}; for (var j = 0; j < attrs.length; j++) { nameObj[attrs[j]] = name + capitalAttrs[j]; } callback.call(context, nameObj); }); }; } /** * Iterate each dimension name. * * @public * @param {Function} callback The parameter is like: * { * name: 'angle', * capital: 'Angle', * axis: 'angleAxis', * axisIndex: 'angleAixs', * index: 'angleIndex' * } * @param {Object} context */ var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']); /** * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'. * dataZoomModels and 'links' make up one or more graphics. * This function finds the graphic where the source dataZoomModel is in. * * @public * @param {Function} forEachNode Node iterator. * @param {Function} forEachEdgeType edgeType iterator * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}} */ function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) { return function (sourceNode) { var result = { nodes: [], records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean). }; forEachEdgeType(function (edgeType) { result.records[edgeType.name] = {}; }); if (!sourceNode) { return result; } absorb(sourceNode, result); var existsLink; do { existsLink = false; forEachNode(processSingleNode); } while (existsLink); function processSingleNode(node) { if (!isNodeAbsorded(node, result) && isLinked(node, result)) { absorb(node, result); existsLink = true; } } return result; }; function isNodeAbsorded(node, result) { return indexOf(result.nodes, node) >= 0; } function isLinked(node, result) { var hasLink = false; forEachEdgeType(function (edgeType) { each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) { result.records[edgeType.name][edgeId] && (hasLink = true); }); }); return hasLink; } function absorb(node, result) { result.nodes.push(node); forEachEdgeType(function (edgeType) { each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) { result.records[edgeType.name][edgeId] = true; }); }); } } var each$23 = each$1; var asc$1 = asc; /** * Operate single axis. * One axis can only operated by one axis operator. * Different dataZoomModels may be defined to operate the same axis. * (i.e. 'inside' data zoom and 'slider' data zoom components) * So dataZoomModels share one axisProxy in that case. * * @class */ var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) { /** * @private * @type {string} */ this._dimName = dimName; /** * @private */ this._axisIndex = axisIndex; /** * @private * @type {Array.<number>} */ this._valueWindow; /** * @private * @type {Array.<number>} */ this._percentWindow; /** * @private * @type {Array.<number>} */ this._dataExtent; /** * {minSpan, maxSpan, minValueSpan, maxValueSpan} * @private * @type {Object} */ this._minMaxSpan; /** * @readOnly * @type {module: echarts/model/Global} */ this.ecModel = ecModel; /** * @private * @type {module: echarts/component/dataZoom/DataZoomModel} */ this._dataZoomModel = dataZoomModel; // /** // * @readOnly // * @private // */ // this.hasSeriesStacked; }; AxisProxy.prototype = { constructor: AxisProxy, /** * Whether the axisProxy is hosted by dataZoomModel. * * @public * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel * @return {boolean} */ hostedBy: function (dataZoomModel) { return this._dataZoomModel === dataZoomModel; }, /** * @return {Array.<number>} Value can only be NaN or finite value. */ getDataValueWindow: function () { return this._valueWindow.slice(); }, /** * @return {Array.<number>} */ getDataPercentWindow: function () { return this._percentWindow.slice(); }, /** * @public * @param {number} axisIndex * @return {Array} seriesModels */ getTargetSeriesModels: function () { var seriesModels = []; var ecModel = this.ecModel; ecModel.eachSeries(function (seriesModel) { if (isCoordSupported(seriesModel.get('coordinateSystem'))) { var dimName = this._dimName; var axisModel = ecModel.queryComponents({ mainType: dimName + 'Axis', index: seriesModel.get(dimName + 'AxisIndex'), id: seriesModel.get(dimName + 'AxisId') })[0]; if (this._axisIndex === (axisModel && axisModel.componentIndex)) { seriesModels.push(seriesModel); } } }, this); return seriesModels; }, getAxisModel: function () { return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex); }, getOtherAxisModel: function () { var axisDim = this._dimName; var ecModel = this.ecModel; var axisModel = this.getAxisModel(); var isCartesian = axisDim === 'x' || axisDim === 'y'; var otherAxisDim; var coordSysIndexName; if (isCartesian) { coordSysIndexName = 'gridIndex'; otherAxisDim = axisDim === 'x' ? 'y' : 'x'; } else { coordSysIndexName = 'polarIndex'; otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle'; } var foundOtherAxisModel; ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) { if ((otherAxisModel.get(coordSysIndexName) || 0) === (axisModel.get(coordSysIndexName) || 0) ) { foundOtherAxisModel = otherAxisModel; } }); return foundOtherAxisModel; }, getMinMaxSpan: function () { return clone(this._minMaxSpan); }, /** * Only calculate by given range and this._dataExtent, do not change anything. * * @param {Object} opt * @param {number} [opt.start] * @param {number} [opt.end] * @param {number} [opt.startValue] * @param {number} [opt.endValue] */ calculateDataWindow: function (opt) { var dataExtent = this._dataExtent; var axisModel = this.getAxisModel(); var scale = axisModel.axis.scale; var rangePropMode = this._dataZoomModel.getRangePropMode(); var percentExtent = [0, 100]; var percentWindow = [ opt.start, opt.end ]; var valueWindow = []; each$23(['startValue', 'endValue'], function (prop) { valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null); }); // Normalize bound. each$23([0, 1], function (idx) { var boundValue = valueWindow[idx]; var boundPercent = percentWindow[idx]; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or // on `valueProp` ('startValue', 'endValue'). The former one is suitable // for cases that a dataZoom component controls multiple axes with different // unit or extent, and the latter one is suitable for accurate zoom by pixel // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`, // but it is awkward that `percentProp` can not be obtained from `valueProp` // accurately (because all of values that are overflow the `dataExtent` will // be calculated to percent '100%'). So we have to use // `dataZoom.getRangePropMode()` to mark which prop is used. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise // it remains its original value. if (rangePropMode[idx] === 'percent') { if (boundPercent == null) { boundPercent = percentExtent[idx]; } // Use scale.parse to math round for category or time axis. boundValue = scale.parse(linearMap( boundPercent, percentExtent, dataExtent, true )); } else { // Calculating `percent` from `value` may be not accurate, because // This calculation can not be inversed, because all of values that // are overflow the `dataExtent` will be calculated to percent '100%' boundPercent = linearMap( boundValue, dataExtent, percentExtent, true ); } // valueWindow[idx] = round(boundValue); // percentWindow[idx] = round(boundPercent); valueWindow[idx] = boundValue; percentWindow[idx] = boundPercent; }); return { valueWindow: asc$1(valueWindow), percentWindow: asc$1(percentWindow) }; }, /** * Notice: reset should not be called before series.restoreData() called, * so it is recommanded to be called in "process stage" but not "model init * stage". * * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel */ reset: function (dataZoomModel) { if (dataZoomModel !== this._dataZoomModel) { return; } var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // this.hasSeriesStacked = false; // each(targetSeries, function (series) { // var data = series.getData(); // var dataDim = data.mapDimension(this._dimName); // var stackedDimension = data.getCalculationInfo('stackedDimension'); // if (stackedDimension && stackedDimension === dataDim) { // this.hasSeriesStacked = true; // } // }, this); var dataWindow = this.calculateDataWindow(dataZoomModel.option); this._valueWindow = dataWindow.valueWindow; this._percentWindow = dataWindow.percentWindow; setMinMaxSpan(this); // Update axis setting then. setAxisModel(this); }, /** * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel */ restore: function (dataZoomModel) { if (dataZoomModel !== this._dataZoomModel) { return; } this._valueWindow = this._percentWindow = null; setAxisModel(this, true); }, /** * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel */ filterData: function (dataZoomModel, api) { if (dataZoomModel !== this._dataZoomModel) { return; } var axisDim = this._dimName; var seriesModels = this.getTargetSeriesModels(); var filterMode = dataZoomModel.get('filterMode'); var valueWindow = this._valueWindow; if (filterMode === 'none') { return; } // FIXME // Toolbox may has dataZoom injected. And if there are stacked bar chart // with NaN data, NaN will be filtered and stack will be wrong. // So we need to force the mode to be set empty. // In fect, it is not a big deal that do not support filterMode-'filter' // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis // selection" some day, which might need "adapt to data extent on the // otherAxis", which is disabled by filterMode-'empty'. // But currently, stack has been fixed to based on value but not index, // so this is not an issue any more. // var otherAxisModel = this.getOtherAxisModel(); // if (dataZoomModel.get('$fromToolbox') // && otherAxisModel // && otherAxisModel.hasSeriesStacked // ) { // filterMode = 'empty'; // } // TODO // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet. // Process series data each$23(seriesModels, function (seriesModel) { var seriesData = seriesModel.getData(); var dataDims = seriesData.mapDimension(axisDim, true); if (filterMode === 'weakFilter') { seriesData.filterSelf(function (dataIndex) { var leftOut; var rightOut; var hasValue; for (var i = 0; i < dataDims.length; i++) { var value = seriesData.get(dataDims[i], dataIndex); var thisHasValue = !isNaN(value); var thisLeftOut = value < valueWindow[0]; var thisRightOut = value > valueWindow[1]; if (thisHasValue && !thisLeftOut && !thisRightOut) { return true; } thisHasValue && (hasValue = true); thisLeftOut && (leftOut = true); thisRightOut && (rightOut = true); } // If both left out and right out, do not filter. return hasValue && leftOut && rightOut; }); } else { each$23(dataDims, function (dim) { if (filterMode === 'empty') { seriesModel.setData( seriesData.map(dim, function (value) { return !isInWindow(value) ? NaN : value; }) ); } else { var range = {}; range[dim] = valueWindow; // console.time('select'); seriesData.selectRange(range); // console.timeEnd('select'); } }); } each$23(dataDims, function (dim) { seriesData.setApproximateExtent(valueWindow, dim); }); }); function isInWindow(value) { return value >= valueWindow[0] && value <= valueWindow[1]; } } }; function calculateDataExtent(axisProxy, axisDim, seriesModels) { var dataExtent = [Infinity, -Infinity]; each$23(seriesModels, function (seriesModel) { var seriesData = seriesModel.getData(); if (seriesData) { each$23(seriesData.mapDimension(axisDim, true), function (dim) { var seriesExtent = seriesData.getApproximateExtent(dim); seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]); seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]); }); } }); if (dataExtent[1] < dataExtent[0]) { dataExtent = [NaN, NaN]; } // It is important to get "consistent" extent when more then one axes is // controlled by a `dataZoom`, otherwise those axes will not be synchronized // when zooming. But it is difficult to know what is "consistent", considering // axes have different type or even different meanings (For example, two // time axes are used to compare data of the same date in different years). // So basically dataZoom just obtains extent by series.data (in category axis // extent can be obtained from axis.data). // Nevertheless, user can set min/max/scale on axes to make extent of axes // consistent. fixExtentByAxis(axisProxy, dataExtent); return dataExtent; } function fixExtentByAxis(axisProxy, dataExtent) { var axisModel = axisProxy.getAxisModel(); var min = axisModel.getMin(true); // For category axis, if min/max/scale are not set, extent is determined // by axis.data by default. var isCategoryAxis = axisModel.get('type') === 'category'; var axisDataLen = isCategoryAxis && axisModel.getCategories().length; if (min != null && min !== 'dataMin' && typeof min !== 'function') { dataExtent[0] = min; } else if (isCategoryAxis) { dataExtent[0] = axisDataLen > 0 ? 0 : NaN; } var max = axisModel.getMax(true); if (max != null && max !== 'dataMax' && typeof max !== 'function') { dataExtent[1] = max; } else if (isCategoryAxis) { dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN; } if (!axisModel.get('scale', true)) { dataExtent[0] > 0 && (dataExtent[0] = 0); dataExtent[1] < 0 && (dataExtent[1] = 0); } // For value axis, if min/max/scale are not set, we just use the extent obtained // by series data, which may be a little different from the extent calculated by // `axisHelper.getScaleExtent`. But the different just affects the experience a // little when zooming. So it will not be fixed until some users require it strongly. return dataExtent; } function setAxisModel(axisProxy, isRestore) { var axisModel = axisProxy.getAxisModel(); var percentWindow = axisProxy._percentWindow; var valueWindow = axisProxy._valueWindow; if (!percentWindow) { return; } // [0, 500]: arbitrary value, guess axis extent. var precision = getPixelPrecision(valueWindow, [0, 500]); precision = Math.min(precision, 20); // isRestore or isFull var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100); axisModel.setRange( useOrigin ? null : +valueWindow[0].toFixed(precision), useOrigin ? null : +valueWindow[1].toFixed(precision) ); } function setMinMaxSpan(axisProxy) { var minMaxSpan = axisProxy._minMaxSpan = {}; var dataZoomModel = axisProxy._dataZoomModel; each$23(['min', 'max'], function (minMax) { minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span'); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan var valueSpan = dataZoomModel.get(minMax + 'ValueSpan'); if (valueSpan != null) { minMaxSpan[minMax + 'ValueSpan'] = valueSpan; valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan); if (valueSpan != null) { var dataExtent = axisProxy._dataExtent; minMaxSpan[minMax + 'Span'] = linearMap( dataExtent[0] + valueSpan, dataExtent, [0, 100], true ); } } }); } var each$22 = each$1; var eachAxisDim = eachAxisDim$1; var DataZoomModel = extendComponentModel({ type: 'dataZoom', dependencies: [ 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series' ], /** * @protected */ defaultOption: { zlevel: 0, z: 4, // Higher than normal component (z: 2). orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'. xAxisIndex: null, // Default the first horizontal category axis. yAxisIndex: null, // Default the first vertical category axis. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'. // 'filter': data items which are out of window will be removed. This option is // applicable when filtering outliers. For each data item, it will be // filtered if one of the relevant dimensions is out of the window. // 'weakFilter': data items which are out of window will be removed. This option // is applicable when filtering outliers. For each data item, it will be // filtered only if all of the relevant dimensions are out of the same // side of the window. // 'empty': data items which are out of window will be set to empty. // This option is applicable when user should not neglect // that there are some data items out of window. // 'none': Do not filter. // Taking line chart as an example, line will be broken in // the filtered points when filterModel is set to 'empty', but // be connected when set to 'filter'. throttle: null, // Dispatch action by the fixed rate, avoid frequency. // default 100. Do not throttle when use null/undefined. // If animation === true and animationDurationUpdate > 0, // default value is 100, otherwise 20. start: 0, // Start percent. 0 ~ 100 end: 100, // End percent. 0 ~ 100 startValue: null, // Start value. If startValue specified, start is ignored. endValue: null, // End value. If endValue specified, end is ignored. minSpan: null, // 0 ~ 100 maxSpan: null, // 0 ~ 100 minValueSpan: null, // The range of dataZoom can not be smaller than that. maxValueSpan: null, // The range of dataZoom can not be larger than that. rangeMode: null // Array, can be 'value' or 'percent'. }, /** * @override */ init: function (option, parentModel, ecModel) { /** * key like x_0, y_1 * @private * @type {Object} */ this._dataIntervalByAxis = {}; /** * @private */ this._dataInfo = {}; /** * key like x_0, y_1 * @private */ this._axisProxies = {}; /** * @readOnly */ this.textStyleModel; /** * @private */ this._autoThrottle = true; /** * 'percent' or 'value' * @private */ this._rangePropMode = ['percent', 'percent']; var rawOption = retrieveRaw(option); this.mergeDefaultAndTheme(option, ecModel); this.doInit(rawOption); }, /** * @override */ mergeOption: function (newOption) { var rawOption = retrieveRaw(newOption); //FIX #2591 merge(this.option, newOption, true); this.doInit(rawOption); }, /** * @protected */ doInit: function (rawOption) { var thisOption = this.option; // Disable realtime view update if canvas is not supported. if (!env$1.canvasSupported) { thisOption.realtime = false; } this._setDefaultThrottle(rawOption); updateRangeUse(this, rawOption); each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) { // start/end has higher priority over startValue/endValue if they // both set, but we should make chart.setOption({endValue: 1000}) // effective, rather than chart.setOption({endValue: 1000, end: null}). if (this._rangePropMode[index] === 'value') { thisOption[names[0]] = null; } // Otherwise do nothing and use the merge result. }, this); this.textStyleModel = this.getModel('textStyle'); this._resetTarget(); this._giveAxisProxies(); }, /** * @private */ _giveAxisProxies: function () { var axisProxies = this._axisProxies; this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) { var axisModel = this.dependentModels[dimNames.axis][axisIndex]; // If exists, share axisProxy with other dataZoomModels. var axisProxy = axisModel.__dzAxisProxy || ( // Use the first dataZoomModel as the main model of axisProxy. axisModel.__dzAxisProxy = new AxisProxy( dimNames.name, axisIndex, this, ecModel ) ); // FIXME // dispose __dzAxisProxy axisProxies[dimNames.name + '_' + axisIndex] = axisProxy; }, this); }, /** * @private */ _resetTarget: function () { var thisOption = this.option; var autoMode = this._judgeAutoMode(); eachAxisDim(function (dimNames) { var axisIndexName = dimNames.axisIndex; thisOption[axisIndexName] = normalizeToArray( thisOption[axisIndexName] ); }, this); if (autoMode === 'axisIndex') { this._autoSetAxisIndex(); } else if (autoMode === 'orient') { this._autoSetOrient(); } }, /** * @private */ _judgeAutoMode: function () { // Auto set only works for setOption at the first time. // The following is user's reponsibility. So using merged // option is OK. var thisOption = this.option; var hasIndexSpecified = false; eachAxisDim(function (dimNames) { // When user set axisIndex as a empty array, we think that user specify axisIndex // but do not want use auto mode. Because empty array may be encountered when // some error occured. if (thisOption[dimNames.axisIndex] != null) { hasIndexSpecified = true; } }, this); var orient = thisOption.orient; if (orient == null && hasIndexSpecified) { return 'orient'; } else if (!hasIndexSpecified) { if (orient == null) { thisOption.orient = 'horizontal'; } return 'axisIndex'; } }, /** * @private */ _autoSetAxisIndex: function () { var autoAxisIndex = true; var orient = this.get('orient', true); var thisOption = this.option; var dependentModels = this.dependentModels; if (autoAxisIndex) { // Find axis that parallel to dataZoom as default. var dimName = orient === 'vertical' ? 'y' : 'x'; if (dependentModels[dimName + 'Axis'].length) { thisOption[dimName + 'AxisIndex'] = [0]; autoAxisIndex = false; } else { each$22(dependentModels.singleAxis, function (singleAxisModel) { if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) { thisOption.singleAxisIndex = [singleAxisModel.componentIndex]; autoAxisIndex = false; } }); } } if (autoAxisIndex) { // Find the first category axis as default. (consider polar) eachAxisDim(function (dimNames) { if (!autoAxisIndex) { return; } var axisIndices = []; var axisModels = this.dependentModels[dimNames.axis]; if (axisModels.length && !axisIndices.length) { for (var i = 0, len = axisModels.length; i < len; i++) { if (axisModels[i].get('type') === 'category') { axisIndices.push(i); } } } thisOption[dimNames.axisIndex] = axisIndices; if (axisIndices.length) { autoAxisIndex = false; } }, this); } if (autoAxisIndex) { // FIXME // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制), // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)? // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified, // dataZoom component auto adopts series that reference to // both xAxis and yAxis which type is 'value'. this.ecModel.eachSeries(function (seriesModel) { if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) { eachAxisDim(function (dimNames) { var axisIndices = thisOption[dimNames.axisIndex]; var axisIndex = seriesModel.get(dimNames.axisIndex); var axisId = seriesModel.get(dimNames.axisId); var axisModel = seriesModel.ecModel.queryComponents({ mainType: dimNames.axis, index: axisIndex, id: axisId })[0]; if (__DEV__) { if (!axisModel) { throw new Error( dimNames.axis + ' "' + retrieve( axisIndex, axisId, 0 ) + '" not found' ); } } axisIndex = axisModel.componentIndex; if (indexOf(axisIndices, axisIndex) < 0) { axisIndices.push(axisIndex); } }); } }, this); } }, /** * @private */ _autoSetOrient: function () { var dim; // Find the first axis this.eachTargetAxis(function (dimNames) { !dim && (dim = dimNames.name); }, this); this.option.orient = dim === 'y' ? 'vertical' : 'horizontal'; }, /** * @private */ _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) { // FIXME // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。 // 例如series.type === scatter时。 var is = true; eachAxisDim(function (dimNames) { var seriesAxisIndex = seriesModel.get(dimNames.axisIndex); var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex]; if (!axisModel || axisModel.get('type') !== axisType) { is = false; } }, this); return is; }, /** * @private */ _setDefaultThrottle: function (rawOption) { // When first time user set throttle, auto throttle ends. if (rawOption.hasOwnProperty('throttle')) { this._autoThrottle = false; } if (this._autoThrottle) { var globalOption = this.ecModel.option; this.option.throttle = (globalOption.animation && globalOption.animationDurationUpdate > 0) ? 100 : 20; } }, /** * @public */ getFirstTargetAxisModel: function () { var firstAxisModel; eachAxisDim(function (dimNames) { if (firstAxisModel == null) { var indices = this.get(dimNames.axisIndex); if (indices.length) { firstAxisModel = this.dependentModels[dimNames.axis][indices[0]]; } } }, this); return firstAxisModel; }, /** * @public * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel */ eachTargetAxis: function (callback, context) { var ecModel = this.ecModel; eachAxisDim(function (dimNames) { each$22( this.get(dimNames.axisIndex), function (axisIndex) { callback.call(context, dimNames, axisIndex, this, ecModel); }, this ); }, this); }, /** * @param {string} dimName * @param {number} axisIndex * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined. */ getAxisProxy: function (dimName, axisIndex) { return this._axisProxies[dimName + '_' + axisIndex]; }, /** * @param {string} dimName * @param {number} axisIndex * @return {module:echarts/model/Model} If not found, return null/undefined. */ getAxisModel: function (dimName, axisIndex) { var axisProxy = this.getAxisProxy(dimName, axisIndex); return axisProxy && axisProxy.getAxisModel(); }, /** * If not specified, set to undefined. * * @public * @param {Object} opt * @param {number} [opt.start] * @param {number} [opt.end] * @param {number} [opt.startValue] * @param {number} [opt.endValue] * @param {boolean} [ignoreUpdateRangeUsg=false] */ setRawRange: function (opt, ignoreUpdateRangeUsg) { var option = this.option; each$22([['start', 'startValue'], ['end', 'endValue']], function (names) { // If only one of 'start' and 'startValue' is not null/undefined, the other // should be cleared, which enable clear the option. // If both of them are not set, keep option with the original value, which // enable use only set start but not set end when calling `dispatchAction`. // The same as 'end' and 'endValue'. if (opt[names[0]] != null || opt[names[1]] != null) { option[names[0]] = opt[names[0]]; option[names[1]] = opt[names[1]]; } }, this); !ignoreUpdateRangeUsg && updateRangeUse(this, opt); }, /** * @public * @return {Array.<number>} [startPercent, endPercent] */ getPercentRange: function () { var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) { return axisProxy.getDataPercentWindow(); } }, /** * @public * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0); * * @param {string} [axisDimName] * @param {number} [axisIndex] * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number. */ getValueRange: function (axisDimName, axisIndex) { if (axisDimName == null && axisIndex == null) { var axisProxy = this.findRepresentativeAxisProxy(); if (axisProxy) { return axisProxy.getDataValueWindow(); } } else { return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow(); } }, /** * @public * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy * corresponding to the axisModel * @return {module:echarts/component/dataZoom/AxisProxy} */ findRepresentativeAxisProxy: function (axisModel) { if (axisModel) { return axisModel.__dzAxisProxy; } // Find the first hosted axisProxy var axisProxies = this._axisProxies; for (var key in axisProxies) { if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) { return axisProxies[key]; } } // If no hosted axis find not hosted axisProxy. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis, // and the option.start or option.end settings are different. The percentRange // should follow axisProxy. // (We encounter this problem in toolbox data zoom.) for (var key in axisProxies) { if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) { return axisProxies[key]; } } }, /** * @return {Array.<string>} */ getRangePropMode: function () { return this._rangePropMode.slice(); } }); function retrieveRaw(option) { var ret = {}; each$22( ['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) { option.hasOwnProperty(name) && (ret[name] = option[name]); } ); return ret; } function updateRangeUse(dataZoomModel, rawOption) { var rangePropMode = dataZoomModel._rangePropMode; var rangeModeInOption = dataZoomModel.get('rangeMode'); each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) { var percentSpecified = rawOption[names[0]] != null; var valueSpecified = rawOption[names[1]] != null; if (percentSpecified && !valueSpecified) { rangePropMode[index] = 'percent'; } else if (!percentSpecified && valueSpecified) { rangePropMode[index] = 'value'; } else if (rangeModeInOption) { rangePropMode[index] = rangeModeInOption[index]; } else if (percentSpecified) { // percentSpecified && valueSpecified rangePropMode[index] = 'percent'; } // else remain its original setting. }); } var DataZoomView = Component.extend({ type: 'dataZoom', render: function (dataZoomModel, ecModel, api, payload) { this.dataZoomModel = dataZoomModel; this.ecModel = ecModel; this.api = api; }, /** * Find the first target coordinate system. * * @protected * @return {Object} { * grid: [ * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1}, * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0}, * ... * ], // cartesians must not be null/undefined. * polar: [ * {model: coord0, axisModels: [axis4], coordIndex: 0}, * ... * ], // polars must not be null/undefined. * singleAxis: [ * {model: coord0, axisModels: [], coordIndex: 0} * ] */ getTargetCoordInfo: function () { var dataZoomModel = this.dataZoomModel; var ecModel = this.ecModel; var coordSysLists = {}; dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) { var axisModel = ecModel.getComponent(dimNames.axis, axisIndex); if (axisModel) { var coordModel = axisModel.getCoordSysModel(); coordModel && save( coordModel, axisModel, coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []), coordModel.componentIndex ); } }, this); function save(coordModel, axisModel, store, coordIndex) { var item; for (var i = 0; i < store.length; i++) { if (store[i].model === coordModel) { item = store[i]; break; } } if (!item) { store.push(item = { model: coordModel, axisModels: [], coordIndex: coordIndex }); } item.axisModels.push(axisModel); } return coordSysLists; } }); var SliderZoomModel = DataZoomModel.extend({ type: 'dataZoom.slider', layoutMode: 'box', /** * @protected */ defaultOption: { show: true, // ph => placeholder. Using placehoder here because // deault value can only be drived in view stage. right: 'ph', // Default align to grid rect. top: 'ph', // Default align to grid rect. width: 'ph', // Default align to grid rect. height: 'ph', // Default align to grid rect. left: null, // Default align to grid rect. bottom: null, // Default align to grid rect. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box, // highest priority, remain for compatibility of // previous version, but not recommended any more. dataBackground: { lineStyle: { color: '#2f4554', width: 0.5, opacity: 0.3 }, areaStyle: { color: 'rgba(47,69,84,0.3)', opacity: 0.3 } }, borderColor: '#ddd', // border color of the box. For compatibility, // if dataBackgroundColor is set, borderColor // is ignored. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle. // handleIcon: 'path://M4.9,17.8c0-1.4,4.5-10.5,5.5-12.4c0-0.1,0.6-1.1,0.9-1.1c0.4,0,0.9,1,0.9,1.1c1.1,2.2,5.4,11,5.4,12.4v17.8c0,1.5-0.6,2.1-1.3,2.1H6.1c-0.7,0-1.3-0.6-1.3-2.1V17.8z', handleIcon: 'M8.2,13.6V3.9H6.3v9.7H3.1v14.9h3.3v9.7h1.8v-9.7h3.3V13.6H8.2z M9.7,24.4H4.8v-1.4h4.9V24.4z M9.7,19.1H4.8v-1.4h4.9V19.1z', // Percent of the slider height handleSize: '100%', handleStyle: { color: '#a7b7cc' }, labelPrecision: null, labelFormatter: null, showDetail: true, showDataShadow: 'auto', // Default auto decision. realtime: true, zoomLock: false, // Whether disable zoom. textStyle: { color: '#333' } } }); var Rect$2 = Rect; var linearMap$2 = linearMap; var asc$2 = asc; var bind$4 = bind; var each$24 = each$1; // Constants var DEFAULT_LOCATION_EDGE_GAP = 7; var DEFAULT_FRAME_BORDER_WIDTH = 1; var DEFAULT_FILLER_SIZE = 30; var HORIZONTAL = 'horizontal'; var VERTICAL = 'vertical'; var LABEL_GAP = 5; var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter']; var SliderZoomView = DataZoomView.extend({ type: 'dataZoom.slider', init: function (ecModel, api) { /** * @private * @type {Object} */ this._displayables = {}; /** * @private * @type {string} */ this._orient; /** * [0, 100] * @private */ this._range; /** * [coord of the first handle, coord of the second handle] * @private */ this._handleEnds; /** * [length, thick] * @private * @type {Array.<number>} */ this._size; /** * @private * @type {number} */ this._handleWidth; /** * @private * @type {number} */ this._handleHeight; /** * @private */ this._location; /** * @private */ this._dragging; /** * @private */ this._dataShadowInfo; this.api = api; }, /** * @override */ render: function (dataZoomModel, ecModel, api, payload) { SliderZoomView.superApply(this, 'render', arguments); createOrUpdate( this, '_dispatchZoomAction', this.dataZoomModel.get('throttle'), 'fixRate' ); this._orient = dataZoomModel.get('orient'); if (this.dataZoomModel.get('show') === false) { this.group.removeAll(); return; } // Notice: this._resetInterval() should not be executed when payload.type // is 'dataZoom', origin this._range should be maintained, otherwise 'pan' // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction, if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) { this._buildView(); } this._updateView(); }, /** * @override */ remove: function () { SliderZoomView.superApply(this, 'remove', arguments); clear(this, '_dispatchZoomAction'); }, /** * @override */ dispose: function () { SliderZoomView.superApply(this, 'dispose', arguments); clear(this, '_dispatchZoomAction'); }, _buildView: function () { var thisGroup = this.group; thisGroup.removeAll(); this._resetLocation(); this._resetInterval(); var barGroup = this._displayables.barGroup = new Group(); this._renderBackground(); this._renderHandle(); this._renderDataShadow(); thisGroup.add(barGroup); this._positionGroup(); }, /** * @private */ _resetLocation: function () { var dataZoomModel = this.dataZoomModel; var api = this.api; // If some of x/y/width/height are not specified, // auto-adapt according to target grid. var coordRect = this._findCoordRect(); var ecSize = {width: api.getWidth(), height: api.getHeight()}; // Default align by coordinate system rect. var positionInfo = this._orient === HORIZONTAL ? { // Why using 'right', because right should be used in vertical, // and it is better to be consistent for dealing with position param merge. right: ecSize.width - coordRect.x - coordRect.width, top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP), width: coordRect.width, height: DEFAULT_FILLER_SIZE } : { // vertical right: DEFAULT_LOCATION_EDGE_GAP, top: coordRect.y, width: DEFAULT_FILLER_SIZE, height: coordRect.height }; // Do not write back to option and replace value 'ph', because // the 'ph' value should be recalculated when resize. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value. each$1(['right', 'top', 'width', 'height'], function (name) { if (layoutParams[name] === 'ph') { layoutParams[name] = positionInfo[name]; } }); var layoutRect = getLayoutRect( layoutParams, ecSize, dataZoomModel.padding ); this._location = {x: layoutRect.x, y: layoutRect.y}; this._size = [layoutRect.width, layoutRect.height]; this._orient === VERTICAL && this._size.reverse(); }, /** * @private */ _positionGroup: function () { var thisGroup = this.group; var location = this._location; var orient = this._orient; // Just use the first axis to determine mapping. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel(); var inverse = targetAxisModel && targetAxisModel.get('inverse'); var barGroup = this._displayables.barGroup; var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup. barGroup.attr( (orient === HORIZONTAL && !inverse) ? {scale: otherAxisInverse ? [1, 1] : [1, -1]} : (orient === HORIZONTAL && inverse) ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]} : (orient === VERTICAL && !inverse) ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2} // Dont use Math.PI, considering shadow direction. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2} ); // Position barGroup var rect = thisGroup.getBoundingRect([barGroup]); thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]); }, /** * @private */ _getViewExtent: function () { return [0, this._size[0]]; }, _renderBackground: function () { var dataZoomModel = this.dataZoomModel; var size = this._size; var barGroup = this._displayables.barGroup; barGroup.add(new Rect$2({ silent: true, shape: { x: 0, y: 0, width: size[0], height: size[1] }, style: { fill: dataZoomModel.get('backgroundColor') }, z2: -40 })); // Click panel, over shadow, below handles. barGroup.add(new Rect$2({ shape: { x: 0, y: 0, width: size[0], height: size[1] }, style: { fill: 'transparent' }, z2: 0, onclick: bind(this._onClickPanelClick, this) })); }, _renderDataShadow: function () { var info = this._dataShadowInfo = this._prepareDataShadowInfo(); if (!info) { return; } var size = this._size; var seriesModel = info.series; var data = seriesModel.getRawData(); var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick : info.otherDim; if (otherDim == null) { return; } var otherDataExtent = data.getDataExtent(otherDim); // Nice extent. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3; otherDataExtent = [ otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset ]; var otherShadowExtent = [0, size[1]]; var thisShadowExtent = [0, size[0]]; var areaPoints = [[size[0], 0], [0, 0]]; var linePoints = []; var step = thisShadowExtent[1] / (data.count() - 1); var thisCoord = 0; // Optimize for large data shadow var stride = Math.round(data.count() / size[0]); var lastIsEmpty; data.each([otherDim], function (value, index) { if (stride > 0 && (index % stride)) { thisCoord += step; return; } // FIXME // Should consider axis.min/axis.max when drawing dataShadow. // FIXME // 应该使用统一的空判断?还是在list里进行空判断? var isEmpty = value == null || isNaN(value) || value === ''; // See #4235. var otherCoord = isEmpty ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value. if (isEmpty && !lastIsEmpty && index) { areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]); linePoints.push([linePoints[linePoints.length - 1][0], 0]); } else if (!isEmpty && lastIsEmpty) { areaPoints.push([thisCoord, 0]); linePoints.push([thisCoord, 0]); } areaPoints.push([thisCoord, otherCoord]); linePoints.push([thisCoord, otherCoord]); thisCoord += step; lastIsEmpty = isEmpty; }); var dataZoomModel = this.dataZoomModel; // var dataBackgroundModel = dataZoomModel.getModel('dataBackground'); this._displayables.barGroup.add(new Polygon({ shape: {points: areaPoints}, style: defaults( {fill: dataZoomModel.get('dataBackgroundColor')}, dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle() ), silent: true, z2: -20 })); this._displayables.barGroup.add(new Polyline({ shape: {points: linePoints}, style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(), silent: true, z2: -19 })); }, _prepareDataShadowInfo: function () { var dataZoomModel = this.dataZoomModel; var showDataShadow = dataZoomModel.get('showDataShadow'); if (showDataShadow === false) { return; } // Find a representative series. var result; var ecModel = this.ecModel; dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) { var seriesModels = dataZoomModel .getAxisProxy(dimNames.name, axisIndex) .getTargetSeriesModels(); each$1(seriesModels, function (seriesModel) { if (result) { return; } if (showDataShadow !== true && indexOf( SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type') ) < 0 ) { return; } var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis; var otherDim = getOtherDim(dimNames.name); var otherAxisInverse; var coordSys = seriesModel.coordinateSystem; if (otherDim != null && coordSys.getOtherAxis) { otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse; } otherDim = seriesModel.getData().mapDimension(otherDim); result = { thisAxis: thisAxis, series: seriesModel, thisDim: dimNames.name, otherDim: otherDim, otherAxisInverse: otherAxisInverse }; }, this); }, this); return result; }, _renderHandle: function () { var displaybles = this._displayables; var handles = displaybles.handles = []; var handleLabels = displaybles.handleLabels = []; var barGroup = this._displayables.barGroup; var size = this._size; var dataZoomModel = this.dataZoomModel; barGroup.add(displaybles.filler = new Rect$2({ draggable: true, cursor: getCursor(this._orient), drift: bind$4(this._onDragMove, this, 'all'), onmousemove: function (e) { // Fot mobile devicem, prevent screen slider on the button. stop(e.event); }, ondragstart: bind$4(this._showDataInfo, this, true), ondragend: bind$4(this._onDragEnd, this), onmouseover: bind$4(this._showDataInfo, this, true), onmouseout: bind$4(this._showDataInfo, this, false), style: { fill: dataZoomModel.get('fillerColor'), textPosition : 'inside' } })); // Frame border. barGroup.add(new Rect$2(subPixelOptimizeRect({ silent: true, shape: { x: 0, y: 0, width: size[0], height: size[1] }, style: { stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'), lineWidth: DEFAULT_FRAME_BORDER_WIDTH, fill: 'rgba(0,0,0,0)' } }))); each$24([0, 1], function (handleIndex) { var path = createIcon( dataZoomModel.get('handleIcon'), { cursor: getCursor(this._orient), draggable: true, drift: bind$4(this._onDragMove, this, handleIndex), onmousemove: function (e) { // Fot mobile devicem, prevent screen slider on the button. stop(e.event); }, ondragend: bind$4(this._onDragEnd, this), onmouseover: bind$4(this._showDataInfo, this, true), onmouseout: bind$4(this._showDataInfo, this, false) }, {x: -1, y: 0, width: 2, height: 2} ); var bRect = path.getBoundingRect(); this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]); this._handleWidth = bRect.width / bRect.height * this._handleHeight; path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle()); var handleColor = dataZoomModel.get('handleColor'); // Compatitable with previous version if (handleColor != null) { path.style.fill = handleColor; } barGroup.add(handles[handleIndex] = path); var textStyleModel = dataZoomModel.textStyleModel; this.group.add( handleLabels[handleIndex] = new Text({ silent: true, invisible: true, style: { x: 0, y: 0, text: '', textVerticalAlign: 'middle', textAlign: 'center', textFill: textStyleModel.getTextColor(), textFont: textStyleModel.getFont() }, z2: 10 })); }, this); }, /** * @private */ _resetInterval: function () { var range = this._range = this.dataZoomModel.getPercentRange(); var viewExtent = this._getViewExtent(); this._handleEnds = [ linearMap$2(range[0], [0, 100], viewExtent, true), linearMap$2(range[1], [0, 100], viewExtent, true) ]; }, /** * @private * @param {(number|string)} handleIndex 0 or 1 or 'all' * @param {number} delta */ _updateInterval: function (handleIndex, delta) { var dataZoomModel = this.dataZoomModel; var handleEnds = this._handleEnds; var viewExtend = this._getViewExtent(); var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan(); var percentExtent = [0, 100]; sliderMove( delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, minMaxSpan.minSpan != null ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null ); this._range = asc$2([ linearMap$2(handleEnds[0], viewExtend, percentExtent, true), linearMap$2(handleEnds[1], viewExtend, percentExtent, true) ]); }, /** * @private */ _updateView: function (nonRealtime) { var displaybles = this._displayables; var handleEnds = this._handleEnds; var handleInterval = asc$2(handleEnds.slice()); var size = this._size; each$24([0, 1], function (handleIndex) { // Handles var handle = displaybles.handles[handleIndex]; var handleHeight = this._handleHeight; handle.attr({ scale: [handleHeight / 2, handleHeight / 2], position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2] }); }, this); // Filler displaybles.filler.setShape({ x: handleInterval[0], y: 0, width: handleInterval[1] - handleInterval[0], height: size[1] }); this._updateDataInfo(nonRealtime); }, /** * @private */ _updateDataInfo: function (nonRealtime) { var dataZoomModel = this.dataZoomModel; var displaybles = this._displayables; var handleLabels = displaybles.handleLabels; var orient = this._orient; var labelTexts = ['', '']; // FIXME // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter) if (dataZoomModel.get('showDetail')) { var axisProxy = dataZoomModel.findRepresentativeAxisProxy(); if (axisProxy) { var axis = axisProxy.getAxisModel().axis; var range = this._range; var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode. ? axisProxy.calculateDataWindow({ start: range[0], end: range[1] }).valueWindow : axisProxy.getDataValueWindow(); labelTexts = [ this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis) ]; } } var orderedHandleEnds = asc$2(this._handleEnds.slice()); setLabel.call(this, 0); setLabel.call(this, 1); function setLabel(handleIndex) { // Label // Text should not transform by barGroup. // Ignore handlers transform var barTransform = getTransform( displaybles.handles[handleIndex].parent, this.group ); var direction = transformDirection( handleIndex === 0 ? 'right' : 'left', barTransform ); var offset = this._handleWidth / 2 + LABEL_GAP; var textPoint = applyTransform$1( [ orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2 ], barTransform ); handleLabels[handleIndex].setStyle({ x: textPoint[0], y: textPoint[1], textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction, textAlign: orient === HORIZONTAL ? direction : 'center', text: labelTexts[handleIndex] }); } }, /** * @private */ _formatLabel: function (value, axis) { var dataZoomModel = this.dataZoomModel; var labelFormatter = dataZoomModel.get('labelFormatter'); var labelPrecision = dataZoomModel.get('labelPrecision'); if (labelPrecision == null || labelPrecision === 'auto') { labelPrecision = axis.getPixelPrecision(); } var valueStr = (value == null || isNaN(value)) ? '' // FIXME Glue code : (axis.type === 'category' || axis.type === 'time') ? axis.scale.getLabel(Math.round(value)) // param of toFixed should less then 20. : value.toFixed(Math.min(labelPrecision, 20)); return isFunction$1(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr; }, /** * @private * @param {boolean} showOrHide true: show, false: hide */ _showDataInfo: function (showOrHide) { // Always show when drgging. showOrHide = this._dragging || showOrHide; var handleLabels = this._displayables.handleLabels; handleLabels[0].attr('invisible', !showOrHide); handleLabels[1].attr('invisible', !showOrHide); }, _onDragMove: function (handleIndex, dx, dy) { this._dragging = true; // Transform dx, dy to bar coordination. var barTransform = this._displayables.barGroup.getLocalTransform(); var vertex = applyTransform$1([dx, dy], barTransform, true); this._updateInterval(handleIndex, vertex[0]); var realtime = this.dataZoomModel.get('realtime'); this._updateView(!realtime); realtime && this._dispatchZoomAction(); }, _onDragEnd: function () { this._dragging = false; this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when // drag end will cause the whole view rerender, which is unnecessary. var realtime = this.dataZoomModel.get('realtime'); !realtime && this._dispatchZoomAction(); }, _onClickPanelClick: function (e) { var size = this._size; var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY); if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1] ) { return; } var handleEnds = this._handleEnds; var center = (handleEnds[0] + handleEnds[1]) / 2; this._updateInterval('all', localPoint[0] - center); this._updateView(); this._dispatchZoomAction(); }, /** * This action will be throttled. * @private */ _dispatchZoomAction: function () { var range = this._range; this.api.dispatchAction({ type: 'dataZoom', from: this.uid, dataZoomId: this.dataZoomModel.id, start: range[0], end: range[1] }); }, /** * @private */ _findCoordRect: function () { // Find the grid coresponding to the first axis referred by dataZoom. var rect; each$24(this.getTargetCoordInfo(), function (coordInfoList) { if (!rect && coordInfoList.length) { var coordSys = coordInfoList[0].model.coordinateSystem; rect = coordSys.getRect && coordSys.getRect(); } }); if (!rect) { var width = this.api.getWidth(); var height = this.api.getHeight(); rect = { x: width * 0.2, y: height * 0.2, width: width * 0.6, height: height * 0.6 }; } return rect; } }); function getOtherDim(thisDim) { // FIXME // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好 var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'}; return map$$1[thisDim]; } function getCursor(orient) { return orient === 'vertical' ? 'ns-resize' : 'ew-resize'; } DataZoomModel.extend({ type: 'dataZoom.inside', /** * @protected */ defaultOption: { disabled: false, // Whether disable this inside zoom. zoomLock: false, // Whether disable zoom but only pan. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'. preventDefaultMouseMove: true } }); // Only create one roam controller for each coordinate system. // one roam controller might be refered by two inside data zoom // components (for example, one for x and one for y). When user // pan or zoom, only dispatch one action for those data zoom // components. var curry$6 = curry; var ATTR$1 = '\0_ec_dataZoom_roams'; /** * @public * @param {module:echarts/ExtensionAPI} api * @param {Object} dataZoomInfo * @param {string} dataZoomInfo.coordId * @param {Function} dataZoomInfo.containsPoint * @param {Array.<string>} dataZoomInfo.allCoordIds * @param {string} dataZoomInfo.dataZoomId * @param {number} dataZoomInfo.throttleRate * @param {Function} dataZoomInfo.panGetRange * @param {Function} dataZoomInfo.zoomGetRange * @param {boolean} [dataZoomInfo.zoomLock] * @param {boolean} [dataZoomInfo.disabled] */ function register$2(api, dataZoomInfo) { var store = giveStore(api); var theDataZoomId = dataZoomInfo.dataZoomId; var theCoordId = dataZoomInfo.coordId; // Do clean when a dataZoom changes its target coordnate system. // Avoid memory leak, dispose all not-used-registered. each$1(store, function (record, coordId) { var dataZoomInfos = record.dataZoomInfos; if (dataZoomInfos[theDataZoomId] && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0 ) { delete dataZoomInfos[theDataZoomId]; record.count--; } }); cleanStore(store); var record = store[theCoordId]; // Create if needed. if (!record) { record = store[theCoordId] = { coordId: theCoordId, dataZoomInfos: {}, count: 0 }; record.controller = createController(api, record); record.dispatchAction = curry(dispatchAction$1, api); } // Update reference of dataZoom. !(record.dataZoomInfos[theDataZoomId]) && record.count++; record.dataZoomInfos[theDataZoomId] = dataZoomInfo; var controllerParams = mergeControllerParams(record.dataZoomInfos); record.controller.enable(controllerParams.controlType, controllerParams.opt); // Consider resize, area should be always updated. record.controller.setPointerChecker(dataZoomInfo.containsPoint); // Update throttle. createOrUpdate( record, 'dispatchAction', dataZoomInfo.throttleRate, 'fixRate' ); } /** * @public * @param {module:echarts/ExtensionAPI} api * @param {string} dataZoomId */ function unregister$1(api, dataZoomId) { var store = giveStore(api); each$1(store, function (record) { record.controller.dispose(); var dataZoomInfos = record.dataZoomInfos; if (dataZoomInfos[dataZoomId]) { delete dataZoomInfos[dataZoomId]; record.count--; } }); cleanStore(store); } /** * @public */ function shouldRecordRange(payload, dataZoomId) { if (payload && payload.type === 'dataZoom' && payload.batch) { for (var i = 0, len = payload.batch.length; i < len; i++) { if (payload.batch[i].dataZoomId === dataZoomId) { return false; } } } return true; } /** * @public */ function generateCoordId(coordModel) { return coordModel.type + '\0_' + coordModel.id; } /** * Key: coordId, value: {dataZoomInfos: [], count, controller} * @type {Array.<Object>} */ function giveStore(api) { // Mount store on zrender instance, so that we do not // need to worry about dispose. var zr = api.getZr(); return zr[ATTR$1] || (zr[ATTR$1] = {}); } function createController(api, newRecord) { var controller = new RoamController(api.getZr()); controller.on('pan', curry$6(onPan, newRecord)); controller.on('zoom', curry$6(onZoom, newRecord)); return controller; } function cleanStore(store) { each$1(store, function (record, coordId) { if (!record.count) { record.controller.dispose(); delete store[coordId]; } }); } function onPan(record, dx, dy, oldX, oldY, newX, newY) { wrapAndDispatch(record, function (info) { return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY); }); } function onZoom(record, scale, mouseX, mouseY) { wrapAndDispatch(record, function (info) { return info.zoomGetRange(record.controller, scale, mouseX, mouseY); }); } function wrapAndDispatch(record, getRange) { var batch = []; each$1(record.dataZoomInfos, function (info) { var range = getRange(info); !info.disabled && range && batch.push({ dataZoomId: info.dataZoomId, start: range[0], end: range[1] }); }); record.dispatchAction(batch); } /** * This action will be throttled. */ function dispatchAction$1(api, batch) { api.dispatchAction({ type: 'dataZoom', batch: batch }); } /** * Merge roamController settings when multiple dataZooms share one roamController. */ function mergeControllerParams(dataZoomInfos) { var controlType; var opt = {}; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated // as string, it is probably revert to reserved word by compress tool. See #7411. var prefix = 'type_'; var typePriority = { 'type_true': 2, 'type_move': 1, 'type_false': 0, 'type_undefined': -1 }; each$1(dataZoomInfos, function (dataZoomInfo) { var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true; if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) { controlType = oneType; } // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys. extend(opt, dataZoomInfo.roamControllerOpt); }); return { controlType: controlType, opt: opt }; } var bind$5 = bind; var InsideZoomView = DataZoomView.extend({ type: 'dataZoom.inside', /** * @override */ init: function (ecModel, api) { /** * 'throttle' is used in this.dispatchAction, so we save range * to avoid missing some 'pan' info. * @private * @type {Array.<number>} */ this._range; }, /** * @override */ render: function (dataZoomModel, ecModel, api, payload) { InsideZoomView.superApply(this, 'render', arguments); // Notice: origin this._range should be maintained, and should not be re-fetched // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom' // info will be missed because of 'throttle' of this.dispatchAction. if (shouldRecordRange(payload, dataZoomModel.id)) { this._range = dataZoomModel.getPercentRange(); } // Reset controllers. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) { var allCoordIds = map(coordInfoList, function (coordInfo) { return generateCoordId(coordInfo.model); }); each$1(coordInfoList, function (coordInfo) { var coordModel = coordInfo.model; var dataZoomOption = dataZoomModel.option; register$2( api, { coordId: generateCoordId(coordModel), allCoordIds: allCoordIds, containsPoint: function (e, x, y) { return coordModel.coordinateSystem.containPoint([x, y]); }, dataZoomId: dataZoomModel.id, throttleRate: dataZoomModel.get('throttle', true), panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName), zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName), zoomLock: dataZoomOption.zoomLock, disabled: dataZoomOption.disabled, roamControllerOpt: { zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel, moveOnMouseMove: dataZoomOption.moveOnMouseMove, preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove } } ); }, this); }, this); }, /** * @override */ dispose: function () { unregister$1(this.api, this.dataZoomModel.id); InsideZoomView.superApply(this, 'dispose', arguments); this._range = null; }, /** * @private */ _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) { var range = this._range.slice(); // Calculate transform by the first axis. var axisModel = coordInfo.axisModels[0]; if (!axisModel) { return; } var directionInfo = getDirectionInfo[coordSysName]( [oldX, oldY], [newX, newY], axisModel, controller, coordInfo ); var percentDelta = directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength; sliderMove(percentDelta, range, [0, 100], 'all'); return (this._range = range); }, /** * @private */ _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) { var range = this._range.slice(); // Calculate transform by the first axis. var axisModel = coordInfo.axisModels[0]; if (!axisModel) { return; } var directionInfo = getDirectionInfo[coordSysName]( null, [mouseX, mouseY], axisModel, controller, coordInfo ); var percentPoint = ( directionInfo.signal > 0 ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel) : (directionInfo.pixel - directionInfo.pixelStart) ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0]; scale = Math.max(1 / scale, 0); range[0] = (range[0] - percentPoint) * scale + percentPoint; range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan(); sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan); return (this._range = range); } }); var getDirectionInfo = { grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) { var axis = axisModel.axis; var ret = {}; var rect = coordInfo.model.coordinateSystem.getRect(); oldPoint = oldPoint || [0, 0]; if (axis.dim === 'x') { ret.pixel = newPoint[0] - oldPoint[0]; ret.pixelLength = rect.width; ret.pixelStart = rect.x; ret.signal = axis.inverse ? 1 : -1; } else { // axis.dim === 'y' ret.pixel = newPoint[1] - oldPoint[1]; ret.pixelLength = rect.height; ret.pixelStart = rect.y; ret.signal = axis.inverse ? -1 : 1; } return ret; }, polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) { var axis = axisModel.axis; var ret = {}; var polar = coordInfo.model.coordinateSystem; var radiusExtent = polar.getRadiusAxis().getExtent(); var angleExtent = polar.getAngleAxis().getExtent(); oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0]; newPoint = polar.pointToCoord(newPoint); if (axisModel.mainType === 'radiusAxis') { ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]); // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]); ret.pixelLength = radiusExtent[1] - radiusExtent[0]; ret.pixelStart = radiusExtent[0]; ret.signal = axis.inverse ? 1 : -1; } else { // 'angleAxis' ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]); // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]); ret.pixelLength = angleExtent[1] - angleExtent[0]; ret.pixelStart = angleExtent[0]; ret.signal = axis.inverse ? -1 : 1; } return ret; }, singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) { var axis = axisModel.axis; var rect = coordInfo.model.coordinateSystem.getRect(); var ret = {}; oldPoint = oldPoint || [0, 0]; if (axis.orient === 'horizontal') { ret.pixel = newPoint[0] - oldPoint[0]; ret.pixelLength = rect.width; ret.pixelStart = rect.x; ret.signal = axis.inverse ? 1 : -1; } else { // 'vertical' ret.pixel = newPoint[1] - oldPoint[1]; ret.pixelLength = rect.height; ret.pixelStart = rect.y; ret.signal = axis.inverse ? -1 : 1; } return ret; } }; registerProcessor({ getTargetSeries: function (ecModel) { var seriesModelMap = createHashMap(); ecModel.eachComponent('dataZoom', function (dataZoomModel) { dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) { var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex); each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) { seriesModelMap.set(seriesModel.uid, seriesModel); }); }); }); return seriesModelMap; }, isOverallFilter: true, // Consider appendData, where filter should be performed. Because data process is // in block mode currently, it is not need to worry about that the overallProgress // execute every frame. overallReset: function (ecModel, api) { ecModel.eachComponent('dataZoom', function (dataZoomModel) { // We calculate window and reset axis here but not in model // init stage and not after action dispatch handler, because // reset should be called after seriesData.restoreData. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) { dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api); }); // Caution: data zoom filtering is order sensitive when using // percent range and no min/max/scale set on axis. // For example, we have dataZoom definition: // [ // {xAxisIndex: 0, start: 30, end: 70}, // {yAxisIndex: 0, start: 20, end: 80} // ] // In this case, [20, 80] of y-dataZoom should be based on data // that have filtered by x-dataZoom using range of [30, 70], // but should not be based on full raw data. Thus sliding // x-dataZoom will change both ranges of xAxis and yAxis, // while sliding y-dataZoom will only change the range of yAxis. // So we should filter x-axis after reset x-axis immediately, // and then reset y-axis and filter y-axis. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) { dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api); }); }); ecModel.eachComponent('dataZoom', function (dataZoomModel) { // Fullfill all of the range props so that user // is able to get them from chart.getOption(). var axisProxy = dataZoomModel.findRepresentativeAxisProxy(); var percentRange = axisProxy.getDataPercentWindow(); var valueRange = axisProxy.getDataValueWindow(); dataZoomModel.setRawRange({ start: percentRange[0], end: percentRange[1], startValue: valueRange[0], endValue: valueRange[1] }, true); }); } }); registerAction('dataZoom', function (payload, ecModel) { var linkedNodesFinder = createLinkedNodesFinder( bind(ecModel.eachComponent, ecModel, 'dataZoom'), eachAxisDim$1, function (model, dimNames) { return model.get(dimNames.axisIndex); } ); var effectedModels = []; ecModel.eachComponent( {mainType: 'dataZoom', query: payload}, function (model, index) { effectedModels.push.apply( effectedModels, linkedNodesFinder(model).nodes ); } ); each$1(effectedModels, function (dataZoomModel, index) { dataZoomModel.setRawRange({ start: payload.start, end: payload.end, startValue: payload.startValue, endValue: payload.endValue }); }); }); /** * DataZoom component entry */ var each$25 = each$1; var preprocessor$2 = function (option) { var visualMap = option && option.visualMap; if (!isArray(visualMap)) { visualMap = visualMap ? [visualMap] : []; } each$25(visualMap, function (opt) { if (!opt) { return; } // rename splitList to pieces if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) { opt.pieces = opt.splitList; delete opt.splitList; } var pieces = opt.pieces; if (pieces && isArray(pieces)) { each$25(pieces, function (piece) { if (isObject$1(piece)) { if (has$1(piece, 'start') && !has$1(piece, 'min')) { piece.min = piece.start; } if (has$1(piece, 'end') && !has$1(piece, 'max')) { piece.max = piece.end; } } }); } }); }; function has$1(obj, name) { return obj && obj.hasOwnProperty && obj.hasOwnProperty(name); } ComponentModel.registerSubTypeDefaulter('visualMap', function (option) { // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used. return ( !option.categories && ( !( option.pieces ? option.pieces.length > 0 : option.splitNumber > 0 ) || option.calculable ) ) ? 'continuous' : 'piecewise'; }); var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT; registerVisual(VISUAL_PRIORITY, { createOnAllSeries: true, reset: function (seriesModel, ecModel) { var resetDefines = []; ecModel.eachComponent('visualMap', function (visualMapModel) { if (!visualMapModel.isTargetSeries(seriesModel)) { return; } resetDefines.push(incrementalApplyVisual( visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimension(seriesModel.getData()) )); }); return resetDefines; } }); // Only support color. registerVisual(VISUAL_PRIORITY, { createOnAllSeries: true, reset: function (seriesModel, ecModel) { var data = seriesModel.getData(); var visualMetaList = []; ecModel.eachComponent('visualMap', function (visualMapModel) { if (visualMapModel.isTargetSeries(seriesModel)) { var visualMeta = visualMapModel.getVisualMeta( bind(getColorVisual, null, seriesModel, visualMapModel) ) || {stops: [], outerColors: []}; var concreteDim = visualMapModel.getDataDimension(data); var dimInfo = data.getDimensionInfo(concreteDim); if (dimInfo != null) { // visualMeta.dimension should be dimension index, but not concrete dimension. visualMeta.dimension = dimInfo.index; visualMetaList.push(visualMeta); } } }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops))); seriesModel.getData().setVisual('visualMeta', visualMetaList); } }); // FIXME // performance and export for heatmap? // value can be Infinity or -Infinity function getColorVisual(seriesModel, visualMapModel, value, valueState) { var mappings = visualMapModel.targetVisuals[valueState]; var visualTypes = VisualMapping.prepareVisualTypes(mappings); var resultVisual = { color: seriesModel.getData().getVisual('color') // default color. }; for (var i = 0, len = visualTypes.length; i < len; i++) { var type = visualTypes[i]; var mapping = mappings[ type === 'opacity' ? '__alphaForOpacity' : type ]; mapping && mapping.applyVisual(value, getVisual, setVisual); } return resultVisual.color; function getVisual(key) { return resultVisual[key]; } function setVisual(key, value) { resultVisual[key] = value; } } /** * @file Visual mapping. */ var visualDefault = { /** * @public */ get: function (visualType, key, isCategory) { var value = clone( (defaultOption$3[visualType] || {})[key] ); return isCategory ? (isArray(value) ? value[value.length - 1] : value) : value; } }; var defaultOption$3 = { color: { active: ['#006edd', '#e0ffff'], inactive: ['rgba(0,0,0,0)'] }, colorHue: { active: [0, 360], inactive: [0, 0] }, colorSaturation: { active: [0.3, 1], inactive: [0, 0] }, colorLightness: { active: [0.9, 0.5], inactive: [0, 0] }, colorAlpha: { active: [0.3, 1], inactive: [0, 0] }, opacity: { active: [0.3, 1], inactive: [0, 0] }, symbol: { active: ['circle', 'roundRect', 'diamond'], inactive: ['none'] }, symbolSize: { active: [10, 50], inactive: [0, 0] } }; var mapVisual$2 = VisualMapping.mapVisual; var eachVisual = VisualMapping.eachVisual; var isArray$3 = isArray; var each$26 = each$1; var asc$3 = asc; var linearMap$3 = linearMap; var noop$2 = noop; var VisualMapModel = extendComponentModel({ type: 'visualMap', dependencies: ['series'], /** * @readOnly * @type {Array.<string>} */ stateList: ['inRange', 'outOfRange'], /** * @readOnly * @type {Array.<string>} */ replacableOptionKeys: [ 'inRange', 'outOfRange', 'target', 'controller', 'color' ], /** * [lowerBound, upperBound] * * @readOnly * @type {Array.<number>} */ dataBound: [-Infinity, Infinity], /** * @readOnly * @type {string|Object} */ layoutMode: {type: 'box', ignoreSize: true}, /** * @protected */ defaultOption: { show: true, zlevel: 0, z: 4, seriesIndex: 'all', // 'all' or null/undefined: all series. // A number or an array of number: the specified series. // set min: 0, max: 200, only for campatible with ec2. // In fact min max should not have default value. min: 0, // min value, must specified if pieces is not specified. max: 200, // max value, must specified if pieces is not specified. dimension: null, inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha', // 'symbol', 'symbolSize' outOfRange: null, // 'color', 'colorHue', 'colorSaturation', // 'colorLightness', 'colorAlpha', // 'symbol', 'symbolSize' left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px) right: null, // The same as left. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px) bottom: 0, // The same as top. itemWidth: null, itemHeight: null, inverse: false, orient: 'vertical', // 'horizontal' ¦ 'vertical' backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ccc', // 值域边框颜色 contentColor: '#5793f3', inactiveColor: '#aaa', borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框) padding: 5, // 值域内边距,单位px,默认各方向内边距为5, // 接受数组分别设定上右下左边距,同css textGap: 10, // precision: 0, // 小数精度,默认为0,无小数点 color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange) formatter: null, text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值 textStyle: { color: '#333' // 值域文字颜色 } }, /** * @protected */ init: function (option, parentModel, ecModel) { /** * @private * @type {Array.<number>} */ this._dataExtent; /** * @readOnly */ this.targetVisuals = {}; /** * @readOnly */ this.controllerVisuals = {}; /** * @readOnly */ this.textStyleModel; /** * [width, height] * @readOnly * @type {Array.<number>} */ this.itemSize; this.mergeDefaultAndTheme(option, ecModel); }, /** * @protected */ optionUpdated: function (newOption, isInit) { var thisOption = this.option; // FIXME // necessary? // Disable realtime view update if canvas is not supported. if (!env$1.canvasSupported) { thisOption.realtime = false; } !isInit && replaceVisualOption( thisOption, newOption, this.replacableOptionKeys ); this.textStyleModel = this.getModel('textStyle'); this.resetItemSize(); this.completeVisualOption(); }, /** * @protected */ resetVisual: function (supplementVisualOption) { var stateList = this.stateList; supplementVisualOption = bind(supplementVisualOption, this); this.controllerVisuals = createVisualMappings( this.option.controller, stateList, supplementVisualOption ); this.targetVisuals = createVisualMappings( this.option.target, stateList, supplementVisualOption ); }, /** * @protected * @return {Array.<number>} An array of series indices. */ getTargetSeriesIndices: function () { var optionSeriesIndex = this.option.seriesIndex; var seriesIndices = []; if (optionSeriesIndex == null || optionSeriesIndex === 'all') { this.ecModel.eachSeries(function (seriesModel, index) { seriesIndices.push(index); }); } else { seriesIndices = normalizeToArray(optionSeriesIndex); } return seriesIndices; }, /** * @public */ eachTargetSeries: function (callback, context) { each$1(this.getTargetSeriesIndices(), function (seriesIndex) { callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex)); }, this); }, /** * @pubilc */ isTargetSeries: function (seriesModel) { var is = false; this.eachTargetSeries(function (model) { model === seriesModel && (is = true); }); return is; }, /** * @example * this.formatValueText(someVal); // format single numeric value to text. * this.formatValueText(someVal, true); // format single category value to text. * this.formatValueText([min, max]); // format numeric min-max to text. * this.formatValueText([this.dataBound[0], max]); // using data lower bound. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound. * * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1]. * @param {boolean} [isCategory=false] Only available when value is number. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval. * @return {string} * @protected */ formatValueText: function(value, isCategory, edgeSymbols) { var option = this.option; var precision = option.precision; var dataBound = this.dataBound; var formatter = option.formatter; var isMinMax; var textValue; edgeSymbols = edgeSymbols || ['<', '>']; if (isArray(value)) { value = value.slice(); isMinMax = true; } textValue = isCategory ? value : (isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value) ); if (isString(formatter)) { return formatter .replace('{value}', isMinMax ? textValue[0] : textValue) .replace('{value2}', isMinMax ? textValue[1] : textValue); } else if (isFunction$1(formatter)) { return isMinMax ? formatter(value[0], value[1]) : formatter(value); } if (isMinMax) { if (value[0] === dataBound[0]) { return edgeSymbols[0] + ' ' + textValue[1]; } else if (value[1] === dataBound[1]) { return edgeSymbols[1] + ' ' + textValue[0]; } else { return textValue[0] + ' - ' + textValue[1]; } } else { // Format single value (includes category case). return textValue; } function toFixed(val) { return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20)); } }, /** * @protected */ resetExtent: function () { var thisOption = this.option; // Can not calculate data extent by data here. // Because series and data may be modified in processing stage. // So we do not support the feature "auto min/max". var extent = asc$3([thisOption.min, thisOption.max]); this._dataExtent = extent; }, /** * @public * @param {module:echarts/data/List} list * @return {string} Concrete dimention. If return null/undefined, * no dimension used. */ getDataDimension: function (list) { var optDim = this.option.dimension; var listDimensions = list.dimensions; if (optDim == null && !listDimensions.length) { return; } if (optDim != null) { return list.getDimension(optDim); } var dimNames = list.dimensions; for (var i = dimNames.length - 1; i >= 0; i--) { var dimName = dimNames[i]; var dimInfo = list.getDimensionInfo(dimName); if (!dimInfo.isCalculationCoord) { return dimName; } } }, /** * @public * @override */ getExtent: function () { return this._dataExtent.slice(); }, /** * @protected */ completeVisualOption: function () { var ecModel = this.ecModel; var thisOption = this.option; var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange}; var target = thisOption.target || (thisOption.target = {}); var controller = thisOption.controller || (thisOption.controller = {}); merge(target, base); // Do not override merge(controller, base); // Do not override var isCategory = this.isCategory(); completeSingle.call(this, target); completeSingle.call(this, controller); completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange'); completeController.call(this, controller); function completeSingle(base) { // Compatible with ec2 dataRange.color. // The mapping order of dataRange.color is: [high value, ..., low value] // whereas inRange.color and outOfRange.color is [low value, ..., high value] // Notice: ec2 has no inverse. if (isArray$3(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake. // So adding color only when no inRange defined. && !base.inRange ) { base.inRange = {color: thisOption.color.slice().reverse()}; } // Compatible with previous logic, always give a defautl color, otherwise // simple config with no inRange and outOfRange will not work. // Originally we use visualMap.color as the default color, but setOption at // the second time the default color will be erased. So we change to use // constant DEFAULT_COLOR. // If user do not want the defualt color, set inRange: {color: null}. base.inRange = base.inRange || {color: ecModel.get('gradientColor')}; // If using shortcut like: {inRange: 'symbol'}, complete default value. each$26(this.stateList, function (state) { var visualType = base[state]; if (isString(visualType)) { var defa = visualDefault.get(visualType, 'active', isCategory); if (defa) { base[state] = {}; base[state][visualType] = defa; } else { // Mark as not specified. delete base[state]; } } }, this); } function completeInactive(base, stateExist, stateAbsent) { var optExist = base[stateExist]; var optAbsent = base[stateAbsent]; if (optExist && !optAbsent) { optAbsent = base[stateAbsent] = {}; each$26(optExist, function (visualData, visualType) { if (!VisualMapping.isValidType(visualType)) { return; } var defa = visualDefault.get(visualType, 'inactive', isCategory); if (defa != null) { optAbsent[visualType] = defa; // Compatibable with ec2: // Only inactive color to rgba(0,0,0,0) can not // make label transparent, so use opacity also. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha') ) { optAbsent.opacity = [0, 0]; } } }); } } function completeController(controller) { var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol; var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize; var inactiveColor = this.get('inactiveColor'); each$26(this.stateList, function (state) { var itemSize = this.itemSize; var visuals = controller[state]; // Set inactive color for controller if no other color // attr (like colorAlpha) specified. if (!visuals) { visuals = controller[state] = { color: isCategory ? inactiveColor : [inactiveColor] }; } // Consistent symbol and symbolSize if not specified. if (visuals.symbol == null) { visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? 'roundRect' : ['roundRect']); } if (visuals.symbolSize == null) { visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]); } // Filter square and none. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) { return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol; }); // Normalize symbolSize var symbolSize = visuals.symbolSize; if (symbolSize != null) { var max = -Infinity; // symbolSize can be object when categories defined. eachVisual(symbolSize, function (value) { value > max && (max = value); }); visuals.symbolSize = mapVisual$2(symbolSize, function (value) { return linearMap$3(value, [0, max], [0, itemSize[0]], true); }); } }, this); } }, /** * @protected */ resetItemSize: function () { this.itemSize = [ parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight')) ]; }, /** * @public */ isCategory: function () { return !!this.option.categories; }, /** * @public * @abstract */ setSelected: noop$2, /** * @public * @abstract * @param {*|module:echarts/data/List} valueOrData * @param {number} dataIndex * @return {string} state See this.stateList */ getValueState: noop$2, /** * FIXME * Do not publish to thirt-part-dev temporarily * util the interface is stable. (Should it return * a function but not visual meta?) * * @pubilc * @abstract * @param {Function} getColorVisual * params: value, valueState * return: color * @return {Object} visualMeta * should includes {stops, outerColors} * outerColor means [colorBeyondMinValue, colorBeyondMaxValue] */ getVisualMeta: noop$2 }); // Constant var DEFAULT_BAR_BOUND = [20, 140]; var ContinuousModel = VisualMapModel.extend({ type: 'visualMap.continuous', /** * @protected */ defaultOption: { align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom' calculable: false, // This prop effect default component type determine, // See echarts/component/visualMap/typeDefaulter. range: null, // selected range. In default case `range` is [min, max] // and can auto change along with modification of min max, // util use specifid a range. realtime: true, // Whether realtime update. itemHeight: null, // The length of the range control edge. itemWidth: null, // The length of the other side. hoverLink: true, // Enable hover highlight. hoverLinkDataSize: null,// The size of hovered data. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle. // If not specified, follow the value of `realtime`. }, /** * @override */ optionUpdated: function (newOption, isInit) { ContinuousModel.superApply(this, 'optionUpdated', arguments); this.resetExtent(); this.resetVisual(function (mappingOption) { mappingOption.mappingMethod = 'linear'; mappingOption.dataExtent = this.getExtent(); }); this._resetRange(); }, /** * @protected * @override */ resetItemSize: function () { ContinuousModel.superApply(this, 'resetItemSize', arguments); var itemSize = this.itemSize; this._orient === 'horizontal' && itemSize.reverse(); (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]); (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]); }, /** * @private */ _resetRange: function () { var dataExtent = this.getExtent(); var range = this.option.range; if (!range || range.auto) { // `range` should always be array (so we dont use other // value like 'auto') for user-friend. (consider getOption). dataExtent.auto = 1; this.option.range = dataExtent; } else if (isArray(range)) { if (range[0] > range[1]) { range.reverse(); } range[0] = Math.max(range[0], dataExtent[0]); range[1] = Math.min(range[1], dataExtent[1]); } }, /** * @protected * @override */ completeVisualOption: function () { VisualMapModel.prototype.completeVisualOption.apply(this, arguments); each$1(this.stateList, function (state) { var symbolSize = this.option.controller[state].symbolSize; if (symbolSize && symbolSize[0] !== symbolSize[1]) { symbolSize[0] = 0; // For good looking. } }, this); }, /** * @override */ setSelected: function (selected) { this.option.range = selected.slice(); this._resetRange(); }, /** * @public */ getSelected: function () { var dataExtent = this.getExtent(); var dataInterval = asc( (this.get('range') || []).slice() ); // Clamp dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]); dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]); dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]); dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]); return dataInterval; }, /** * @override */ getValueState: function (value) { var range = this.option.range; var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'. // range[1] is processed likewise. return ( (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ) ? 'inRange' : 'outOfRange'; }, /** * @params {Array.<number>} range target value: range[0] <= value && value <= range[1] * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...] */ findTargetDataIndices: function (range) { var result = []; this.eachTargetSeries(function (seriesModel) { var dataIndices = []; var data = seriesModel.getData(); data.each(this.getDataDimension(data), function (value, dataIndex) { range[0] <= value && value <= range[1] && dataIndices.push(dataIndex); }, this); result.push({seriesId: seriesModel.id, dataIndex: dataIndices}); }, this); return result; }, /** * @implement */ getVisualMeta: function (getColorVisual) { var oVals = getColorStopValues(this, 'outOfRange', this.getExtent()); var iVals = getColorStopValues(this, 'inRange', this.option.range.slice()); var stops = []; function setStop(value, valueState) { stops.push({ value: value, color: getColorVisual(value, valueState) }); } // Format to: outOfRange -- inRange -- outOfRange. var iIdx = 0; var oIdx = 0; var iLen = iVals.length; var oLen = oVals.length; for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) { // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored. if (oVals[oIdx] < iVals[iIdx]) { setStop(oVals[oIdx], 'outOfRange'); } } for (var first = 1; iIdx < iLen; iIdx++, first = 0) { // If range is full, value beyond min, max will be clamped. // make a singularity first && stops.length && setStop(iVals[iIdx], 'outOfRange'); setStop(iVals[iIdx], 'inRange'); } for (var first = 1; oIdx < oLen; oIdx++) { if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) { // make a singularity if (first) { stops.length && setStop(stops[stops.length - 1].value, 'outOfRange'); first = 0; } setStop(oVals[oIdx], 'outOfRange'); } } var stopsLen = stops.length; return { stops: stops, outerColors: [ stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent' ] }; } }); function getColorStopValues(visualMapModel, valueState, dataExtent) { if (dataExtent[0] === dataExtent[1]) { return dataExtent.slice(); } // When using colorHue mapping, it is not linear color any more. // Moreover, canvas gradient seems not to be accurate linear. // FIXME // Should be arbitrary value 100? or based on pixel size? var count = 200; var step = (dataExtent[1] - dataExtent[0]) / count; var value = dataExtent[0]; var stopValues = []; for (var i = 0; i <= count && value < dataExtent[1]; i++) { stopValues.push(value); value += step; } stopValues.push(dataExtent[1]); return stopValues; } var VisualMapView = extendComponentView({ type: 'visualMap', /** * @readOnly * @type {Object} */ autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1}, init: function (ecModel, api) { /** * @readOnly * @type {module:echarts/model/Global} */ this.ecModel = ecModel; /** * @readOnly * @type {module:echarts/ExtensionAPI} */ this.api = api; /** * @readOnly * @type {module:echarts/component/visualMap/visualMapModel} */ this.visualMapModel; }, /** * @protected */ render: function (visualMapModel, ecModel, api, payload) { this.visualMapModel = visualMapModel; if (visualMapModel.get('show') === false) { this.group.removeAll(); return; } this.doRender.apply(this, arguments); }, /** * @protected */ renderBackground: function (group) { var visualMapModel = this.visualMapModel; var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0); var rect = group.getBoundingRect(); group.add(new Rect({ z2: -1, // Lay background rect on the lowest layer. silent: true, shape: { x: rect.x - padding[3], y: rect.y - padding[0], width: rect.width + padding[3] + padding[1], height: rect.height + padding[0] + padding[2] }, style: { fill: visualMapModel.get('backgroundColor'), stroke: visualMapModel.get('borderColor'), lineWidth: visualMapModel.get('borderWidth') } })); }, /** * @protected * @param {number} targetValue can be Infinity or -Infinity * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize' * @param {Object} [opts] * @param {string=} [opts.forceState] Specify state, instead of using getValueState method. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget. * @return {*} Visual value. */ getControllerVisual: function (targetValue, visualCluster, opts) { opts = opts || {}; var forceState = opts.forceState; var visualMapModel = this.visualMapModel; var visualObj = {}; // Default values. if (visualCluster === 'symbol') { visualObj.symbol = visualMapModel.get('itemSymbol'); } if (visualCluster === 'color') { var defaultColor = visualMapModel.get('contentColor'); visualObj.color = defaultColor; } function getter(key) { return visualObj[key]; } function setter(key, value) { visualObj[key] = value; } var mappings = visualMapModel.controllerVisuals[ forceState || visualMapModel.getValueState(targetValue) ]; var visualTypes = VisualMapping.prepareVisualTypes(mappings); each$1(visualTypes, function (type) { var visualMapping = mappings[type]; if (opts.convertOpacityToAlpha && type === 'opacity') { type = 'colorAlpha'; visualMapping = mappings.__alphaForOpacity; } if (VisualMapping.dependsOn(type, visualCluster)) { visualMapping && visualMapping.applyVisual( targetValue, getter, setter ); } }); return visualObj[visualCluster]; }, /** * @protected */ positionGroup: function (group) { var model = this.visualMapModel; var api = this.api; positionElement( group, model.getBoxLayoutParams(), {width: api.getWidth(), height: api.getHeight()} ); }, /** * @protected * @abstract */ doRender: noop }); /** * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\ * @param {module:echarts/ExtensionAPI} api * @param {Array.<number>} itemSize always [short, long] * @return {string} 'left' or 'right' or 'top' or 'bottom' */ function getItemAlign(visualMapModel, api, itemSize) { var modelOption = visualMapModel.option; var itemAlign = modelOption.align; if (itemAlign != null && itemAlign !== 'auto') { return itemAlign; } // Auto decision align. var ecSize = {width: api.getWidth(), height: api.getHeight()}; var realIndex = modelOption.orient === 'horizontal' ? 1 : 0; var paramsSet = [ ['left', 'right', 'width'], ['top', 'bottom', 'height'] ]; var reals = paramsSet[realIndex]; var fakeValue = [0, null, 10]; var layoutInput = {}; for (var i = 0; i < 3; i++) { layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i]; layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]]; } var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex]; var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding); return reals[ (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1 ]; } /** * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and * dataIndexInside means filtered index. */ function convertDataIndex(batch) { each$1(batch || [], function (batchItem) { if (batch.dataIndex != null) { batch.dataIndexInside = batch.dataIndex; batch.dataIndex = null; } }); return batch; } var linearMap$4 = linearMap; var each$27 = each$1; var mathMin$7 = Math.min; var mathMax$7 = Math.max; // Arbitrary value var HOVER_LINK_SIZE = 12; var HOVER_LINK_OUT = 6; // Notice: // Any "interval" should be by the order of [low, high]. // "handle0" (handleIndex === 0) maps to // low data value: this._dataInterval[0] and has low coord. // "handle1" (handleIndex === 1) maps to // high data value: this._dataInterval[1] and has high coord. // The logic of transform is implemented in this._createBarGroup. var ContinuousView = VisualMapView.extend({ type: 'visualMap.continuous', /** * @override */ init: function () { ContinuousView.superApply(this, 'init', arguments); /** * @private */ this._shapes = {}; /** * @private */ this._dataInterval = []; /** * @private */ this._handleEnds = []; /** * @private */ this._orient; /** * @private */ this._useHandle; /** * @private */ this._hoverLinkDataIndices = []; /** * @private */ this._dragging; /** * @private */ this._hovering; }, /** * @protected * @override */ doRender: function (visualMapModel, ecModel, api, payload) { if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) { this._buildView(); } }, /** * @private */ _buildView: function () { this.group.removeAll(); var visualMapModel = this.visualMapModel; var thisGroup = this.group; this._orient = visualMapModel.get('orient'); this._useHandle = visualMapModel.get('calculable'); this._resetInterval(); this._renderBar(thisGroup); var dataRangeText = visualMapModel.get('text'); this._renderEndsText(thisGroup, dataRangeText, 0); this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation. this._updateView(true); // After updating view, inner shapes is built completely, // and then background can be rendered. this.renderBackground(thisGroup); // Real update view this._updateView(); this._enableHoverLinkToSeries(); this._enableHoverLinkFromSeries(); this.positionGroup(thisGroup); }, /** * @private */ _renderEndsText: function (group, dataRangeText, endsIndex) { if (!dataRangeText) { return; } // Compatible with ec2, text[0] map to high value, text[1] map low value. var text = dataRangeText[1 - endsIndex]; text = text != null ? text + '' : ''; var visualMapModel = this.visualMapModel; var textGap = visualMapModel.get('textGap'); var itemSize = visualMapModel.itemSize; var barGroup = this._shapes.barGroup; var position = this._applyTransform( [ itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap ], barGroup ); var align = this._applyTransform( endsIndex === 0 ? 'bottom' : 'top', barGroup ); var orient = this._orient; var textStyleModel = this.visualMapModel.textStyleModel; this.group.add(new Text({ style: { x: position[0], y: position[1], textVerticalAlign: orient === 'horizontal' ? 'middle' : align, textAlign: orient === 'horizontal' ? align : 'center', text: text, textFont: textStyleModel.getFont(), textFill: textStyleModel.getTextColor() } })); }, /** * @private */ _renderBar: function (targetGroup) { var visualMapModel = this.visualMapModel; var shapes = this._shapes; var itemSize = visualMapModel.itemSize; var orient = this._orient; var useHandle = this._useHandle; var itemAlign = getItemAlign(visualMapModel, this.api, itemSize); var barGroup = shapes.barGroup = this._createBarGroup(itemAlign); // Bar barGroup.add(shapes.outOfRange = createPolygon()); barGroup.add(shapes.inRange = createPolygon( null, useHandle ? getCursor$1(this._orient) : null, bind(this._dragHandle, this, 'all', false), bind(this._dragHandle, this, 'all', true) )); var textRect = visualMapModel.textStyleModel.getTextRect('国'); var textSize = mathMax$7(textRect.width, textRect.height); // Handle if (useHandle) { shapes.handleThumbs = []; shapes.handleLabels = []; shapes.handleLabelPoints = []; this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign); this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign); } this._createIndicator(barGroup, itemSize, textSize, orient); targetGroup.add(barGroup); }, /** * @private */ _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) { var onDrift = bind(this._dragHandle, this, handleIndex, false); var onDragEnd = bind(this._dragHandle, this, handleIndex, true); var handleThumb = createPolygon( createHandlePoints(handleIndex, textSize), getCursor$1(this._orient), onDrift, onDragEnd ); handleThumb.position[0] = itemSize[0]; barGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by // transform (orient/inverse). So label is built separately but not // use zrender/graphic/helper/RectText, and is located based on view // group (according to handleLabelPoint) but not barGroup. var textStyleModel = this.visualMapModel.textStyleModel; var handleLabel = new Text({ draggable: true, drift: onDrift, onmousemove: function (e) { // Fot mobile devicem, prevent screen slider on the button. stop(e.event); }, ondragend: onDragEnd, style: { x: 0, y: 0, text: '', textFont: textStyleModel.getFont(), textFill: textStyleModel.getTextColor() } }); this.group.add(handleLabel); var handleLabelPoint = [ orient === 'horizontal' ? textSize / 2 : textSize * 1.5, orient === 'horizontal' ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5)) : (handleIndex === 0 ? -textSize / 2 : textSize / 2) ]; var shapes = this._shapes; shapes.handleThumbs[handleIndex] = handleThumb; shapes.handleLabelPoints[handleIndex] = handleLabelPoint; shapes.handleLabels[handleIndex] = handleLabel; }, /** * @private */ _createIndicator: function (barGroup, itemSize, textSize, orient) { var indicator = createPolygon([[0, 0]], 'move'); indicator.position[0] = itemSize[0]; indicator.attr({invisible: true, silent: true}); barGroup.add(indicator); var textStyleModel = this.visualMapModel.textStyleModel; var indicatorLabel = new Text({ silent: true, invisible: true, style: { x: 0, y: 0, text: '', textFont: textStyleModel.getFont(), textFill: textStyleModel.getTextColor() } }); this.group.add(indicatorLabel); var indicatorLabelPoint = [ orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3, 0 ]; var shapes = this._shapes; shapes.indicator = indicator; shapes.indicatorLabel = indicatorLabel; shapes.indicatorLabelPoint = indicatorLabelPoint; }, /** * @private */ _dragHandle: function (handleIndex, isEnd, dx, dy) { if (!this._useHandle) { return; } this._dragging = !isEnd; if (!isEnd) { // Transform dx, dy to bar coordination. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true); this._updateInterval(handleIndex, vertex[1]); // Considering realtime, update view should be executed // before dispatch action. this._updateView(); } // dragEnd do not dispatch action when realtime. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line this.api.dispatchAction({ type: 'selectDataRange', from: this.uid, visualMapId: this.visualMapModel.id, selected: this._dataInterval.slice() }); } if (isEnd) { !this._hovering && this._clearHoverLinkToSeries(); } else if (useHoverLinkOnHandle(this.visualMapModel)) { this._doHoverLinkToSeries(this._handleEnds[handleIndex], false); } }, /** * @private */ _resetInterval: function () { var visualMapModel = this.visualMapModel; var dataInterval = this._dataInterval = visualMapModel.getSelected(); var dataExtent = visualMapModel.getExtent(); var sizeExtent = [0, visualMapModel.itemSize[1]]; this._handleEnds = [ linearMap$4(dataInterval[0], dataExtent, sizeExtent, true), linearMap$4(dataInterval[1], dataExtent, sizeExtent, true) ]; }, /** * @private * @param {(number|string)} handleIndex 0 or 1 or 'all' * @param {number} dx * @param {number} dy */ _updateInterval: function (handleIndex, delta) { delta = delta || 0; var visualMapModel = this.visualMapModel; var handleEnds = this._handleEnds; var sizeExtent = [0, visualMapModel.itemSize[1]]; sliderMove( delta, handleEnds, sizeExtent, handleIndex, // cross is forbiden 0 ); var dataExtent = visualMapModel.getExtent(); // Update data interval. this._dataInterval = [ linearMap$4(handleEnds[0], sizeExtent, dataExtent, true), linearMap$4(handleEnds[1], sizeExtent, dataExtent, true) ]; }, /** * @private */ _updateView: function (forSketch) { var visualMapModel = this.visualMapModel; var dataExtent = visualMapModel.getExtent(); var shapes = this._shapes; var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]]; var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds; var visualInRange = this._createBarVisual( this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange' ); var visualOutOfRange = this._createBarVisual( dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange' ); shapes.inRange .setStyle({ fill: visualInRange.barColor, opacity: visualInRange.opacity }) .setShape('points', visualInRange.barPoints); shapes.outOfRange .setStyle({ fill: visualOutOfRange.barColor, opacity: visualOutOfRange.opacity }) .setShape('points', visualOutOfRange.barPoints); this._updateHandle(inRangeHandleEnds, visualInRange); }, /** * @private */ _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) { var opts = { forceState: forceState, convertOpacityToAlpha: true }; var colorStops = this._makeColorGradient(dataInterval, opts); var symbolSizes = [ this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts) ]; var barPoints = this._createBarPoints(handleEnds, symbolSizes); return { barColor: new LinearGradient(0, 0, 0, 1, colorStops), barPoints: barPoints, handlesColor: [ colorStops[0].color, colorStops[colorStops.length - 1].color ] }; }, /** * @private */ _makeColorGradient: function (dataInterval, opts) { // Considering colorHue, which is not linear, so we have to sample // to calculate gradient color stops, but not only caculate head // and tail. var sampleNumber = 100; // Arbitrary value. var colorStops = []; var step = (dataInterval[1] - dataInterval[0]) / sampleNumber; colorStops.push({ color: this.getControllerVisual(dataInterval[0], 'color', opts), offset: 0 }); for (var i = 1; i < sampleNumber; i++) { var currValue = dataInterval[0] + step * i; if (currValue > dataInterval[1]) { break; } colorStops.push({ color: this.getControllerVisual(currValue, 'color', opts), offset: i / sampleNumber }); } colorStops.push({ color: this.getControllerVisual(dataInterval[1], 'color', opts), offset: 1 }); return colorStops; }, /** * @private */ _createBarPoints: function (handleEnds, symbolSizes) { var itemSize = this.visualMapModel.itemSize; return [ [itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]] ]; }, /** * @private */ _createBarGroup: function (itemAlign) { var orient = this._orient; var inverse = this.visualMapModel.get('inverse'); return new Group( (orient === 'horizontal' && !inverse) ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2} : (orient === 'horizontal' && inverse) ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2} : (orient === 'vertical' && !inverse) ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]} : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]} ); }, /** * @private */ _updateHandle: function (handleEnds, visualInRange) { if (!this._useHandle) { return; } var shapes = this._shapes; var visualMapModel = this.visualMapModel; var handleThumbs = shapes.handleThumbs; var handleLabels = shapes.handleLabels; each$27([0, 1], function (handleIndex) { var handleThumb = handleThumbs[handleIndex]; handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]); handleThumb.position[1] = handleEnds[handleIndex]; // Update handle label position. var textPoint = applyTransform$1( shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group) ); handleLabels[handleIndex].setStyle({ x: textPoint[0], y: textPoint[1], text: visualMapModel.formatValueText(this._dataInterval[handleIndex]), textVerticalAlign: 'middle', textAlign: this._applyTransform( this._orient === 'horizontal' ? (handleIndex === 0 ? 'bottom' : 'top') : 'left', shapes.barGroup ) }); }, this); }, /** * @private * @param {number} cursorValue * @param {number} textValue * @param {string} [rangeSymbol] * @param {number} [halfHoverLinkSize] */ _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) { var visualMapModel = this.visualMapModel; var dataExtent = visualMapModel.getExtent(); var itemSize = visualMapModel.itemSize; var sizeExtent = [0, itemSize[1]]; var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true); var shapes = this._shapes; var indicator = shapes.indicator; if (!indicator) { return; } indicator.position[1] = pos; indicator.attr('invisible', false); indicator.setShape('points', createIndicatorPoints( !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1] )); var opts = {convertOpacityToAlpha: true}; var color = this.getControllerVisual(cursorValue, 'color', opts); indicator.setStyle('fill', color); // Update handle label position. var textPoint = applyTransform$1( shapes.indicatorLabelPoint, getTransform(indicator, this.group) ); var indicatorLabel = shapes.indicatorLabel; indicatorLabel.attr('invisible', false); var align = this._applyTransform('left', shapes.barGroup); var orient = this._orient; indicatorLabel.setStyle({ text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue), textVerticalAlign: orient === 'horizontal' ? align : 'middle', textAlign: orient === 'horizontal' ? 'center' : align, x: textPoint[0], y: textPoint[1] }); }, /** * @private */ _enableHoverLinkToSeries: function () { var self = this; this._shapes.barGroup .on('mousemove', function (e) { self._hovering = true; if (!self._dragging) { var itemSize = self.visualMapModel.itemSize; var pos = self._applyTransform( [e.offsetX, e.offsetY], self._shapes.barGroup, true, true ); // For hover link show when hover handle, which might be // below or upper than sizeExtent. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]); self._doHoverLinkToSeries( pos[1], 0 <= pos[0] && pos[0] <= itemSize[0] ); } }) .on('mouseout', function () { // When mouse is out of handle, hoverLink still need // to be displayed when realtime is set as false. self._hovering = false; !self._dragging && self._clearHoverLinkToSeries(); }); }, /** * @private */ _enableHoverLinkFromSeries: function () { var zr = this.api.getZr(); if (this.visualMapModel.option.hoverLink) { zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this); zr.on('mouseout', this._hideIndicator, this); } else { this._clearHoverLinkFromSeries(); } }, /** * @private */ _doHoverLinkToSeries: function (cursorPos, hoverOnBar) { var visualMapModel = this.visualMapModel; var itemSize = visualMapModel.itemSize; if (!visualMapModel.option.hoverLink) { return; } var sizeExtent = [0, itemSize[1]]; var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]); var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent); var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize]; var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true); var valueRange = [ linearMap$4(hoverRange[0], sizeExtent, dataExtent, true), linearMap$4(hoverRange[1], sizeExtent, dataExtent, true) ]; // Consider data range is out of visualMap range, see test/visualMap-continuous.html, // where china and india has very large population. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity); hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle, // otherwise labels overlap, especially when dragging. if (hoverOnBar) { if (valueRange[0] === -Infinity) { this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize); } else if (valueRange[1] === Infinity) { this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize); } else { this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize); } } // When realtime is set as false, handles, which are in barGroup, // also trigger hoverLink, which help user to realize where they // focus on when dragging. (see test/heatmap-large.html) // When realtime is set as true, highlight will not show when hover // handle, because the label on handle, which displays a exact value // but not range, might mislead users. var oldBatch = this._hoverLinkDataIndices; var newBatch = []; if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) { newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange); } var resultBatches = compressBatches(oldBatch, newBatch); this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0])); this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1])); }, /** * @private */ _hoverLinkFromSeriesMouseOver: function (e) { var el = e.target; var visualMapModel = this.visualMapModel; if (!el || el.dataIndex == null) { return; } var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex); if (!visualMapModel.isTargetSeries(dataModel)) { return; } var data = dataModel.getData(el.dataType); var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true); if (!isNaN(value)) { this._showIndicator(value, value); } }, /** * @private */ _hideIndicator: function () { var shapes = this._shapes; shapes.indicator && shapes.indicator.attr('invisible', true); shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true); }, /** * @private */ _clearHoverLinkToSeries: function () { this._hideIndicator(); var indices = this._hoverLinkDataIndices; this._dispatchHighDown('downplay', convertDataIndex(indices)); indices.length = 0; }, /** * @private */ _clearHoverLinkFromSeries: function () { this._hideIndicator(); var zr = this.api.getZr(); zr.off('mouseover', this._hoverLinkFromSeriesMouseOver); zr.off('mouseout', this._hideIndicator); }, /** * @private */ _applyTransform: function (vertex, element, inverse, global) { var transform = getTransform(element, global ? null : this.group); return graphic[ isArray(vertex) ? 'applyTransform' : 'transformDirection' ](vertex, transform, inverse); }, /** * @private */ _dispatchHighDown: function (type, batch) { batch && batch.length && this.api.dispatchAction({ type: type, batch: batch }); }, /** * @override */ dispose: function () { this._clearHoverLinkFromSeries(); this._clearHoverLinkToSeries(); }, /** * @override */ remove: function () { this._clearHoverLinkFromSeries(); this._clearHoverLinkToSeries(); } }); function createPolygon(points, cursor, onDrift, onDragEnd) { return new Polygon({ shape: {points: points}, draggable: !!onDrift, cursor: cursor, drift: onDrift, onmousemove: function (e) { // Fot mobile devicem, prevent screen slider on the button. stop(e.event); }, ondragend: onDragEnd }); } function createHandlePoints(handleIndex, textSize) { return handleIndex === 0 ? [[0, 0], [textSize, 0], [textSize, -textSize]] : [[0, 0], [textSize, 0], [textSize, textSize]]; } function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) { return isRange ? [ // indicate range [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))], [HOVER_LINK_OUT, 0], [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))] ] : [ // indicate single value [0, 0], [5, -5], [5, 5] ]; } function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) { var halfHoverLinkSize = HOVER_LINK_SIZE / 2; var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize'); if (hoverLinkDataSize) { halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2; } return halfHoverLinkSize; } function useHoverLinkOnHandle(visualMapModel) { var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle'); return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle); } function getCursor$1(orient) { return orient === 'vertical' ? 'ns-resize' : 'ew-resize'; } var actionInfo$2 = { type: 'selectDataRange', event: 'dataRangeSelected', // FIXME use updateView appears wrong update: 'update' }; registerAction(actionInfo$2, function (payload, ecModel) { ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) { model.setSelected(payload.selected); }); }); /** * DataZoom component entry */ registerPreprocessor(preprocessor$2); var PiecewiseModel = VisualMapModel.extend({ type: 'visualMap.piecewise', /** * Order Rule: * * option.categories / option.pieces / option.text / option.selected: * If !option.inverse, * Order when vertical: ['top', ..., 'bottom']. * Order when horizontal: ['left', ..., 'right']. * If option.inverse, the meaning of * the order should be reversed. * * this._pieceList: * The order is always [low, ..., high]. * * Mapping from location to low-high: * If !option.inverse * When vertical, top is high. * When horizontal, right is high. * If option.inverse, reverse. */ /** * @protected */ defaultOption: { selected: null, // Object. If not specified, means selected. // When pieces and splitNumber: {'0': true, '5': true} // When categories: {'cate1': false, 'cate3': true} // When selected === false, means all unselected. minOpen: false, // Whether include values that smaller than `min`. maxOpen: false, // Whether include values that bigger than `max`. align: 'auto', // 'auto', 'left', 'right' itemWidth: 20, // When put the controller vertically, it is the length of // horizontal side of each item. Otherwise, vertical side. itemHeight: 14, // When put the controller vertically, it is the length of // vertical side of each item. Otherwise, horizontal side. itemSymbol: 'roundRect', pieceList: null, // Each item is Object, with some of those attrs: // {min, max, lt, gt, lte, gte, value, // color, colorSaturation, colorAlpha, opacity, // symbol, symbolSize}, which customize the range or visual // coding of the certain piece. Besides, see "Order Rule". categories: null, // category names, like: ['some1', 'some2', 'some3']. // Attr min/max are ignored when categories set. See "Order Rule" splitNumber: 5, // If set to 5, auto split five pieces equally. // If set to 0 and component type not set, component type will be // determined as "continuous". (It is less reasonable but for ec2 // compatibility, see echarts/component/visualMap/typeDefaulter) selectedMode: 'multiple', // Can be 'multiple' or 'single'. itemGap: 10, // The gap between two items, in px. hoverLink: true, // Enable hover highlight. showLabel: null // By default, when text is used, label will hide (the logic // is remained for compatibility reason) }, /** * @override */ optionUpdated: function (newOption, isInit) { PiecewiseModel.superApply(this, 'optionUpdated', arguments); /** * The order is always [low, ..., high]. * [{text: string, interval: Array.<number>}, ...] * @private * @type {Array.<Object>} */ this._pieceList = []; this.resetExtent(); /** * 'pieces', 'categories', 'splitNumber' * @type {string} */ var mode = this._mode = this._determineMode(); resetMethods[this._mode].call(this); this._resetSelected(newOption, isInit); var categories = this.option.categories; this.resetVisual(function (mappingOption, state) { if (mode === 'categories') { mappingOption.mappingMethod = 'category'; mappingOption.categories = clone(categories); } else { mappingOption.dataExtent = this.getExtent(); mappingOption.mappingMethod = 'piecewise'; mappingOption.pieceList = map(this._pieceList, function (piece) { var piece = clone(piece); if (state !== 'inRange') { // FIXME // outOfRange do not support special visual in pieces. piece.visual = null; } return piece; }); } }); }, /** * @protected * @override */ completeVisualOption: function () { // Consider this case: // visualMap: { // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}] // } // where no inRange/outOfRange set but only pieces. So we should make // default inRange/outOfRange for this case, otherwise visuals that only // appear in `pieces` will not be taken into account in visual encoding. var option = this.option; var visualTypesInPieces = {}; var visualTypes = VisualMapping.listVisualTypes(); var isCategory = this.isCategory(); each$1(option.pieces, function (piece) { each$1(visualTypes, function (visualType) { if (piece.hasOwnProperty(visualType)) { visualTypesInPieces[visualType] = 1; } }); }); each$1(visualTypesInPieces, function (v, visualType) { var exists = 0; each$1(this.stateList, function (state) { exists |= has(option, state, visualType) || has(option.target, state, visualType); }, this); !exists && each$1(this.stateList, function (state) { (option[state] || (option[state] = {}))[visualType] = visualDefault.get( visualType, state === 'inRange' ? 'active' : 'inactive', isCategory ); }); }, this); function has(obj, state, visualType) { return obj && obj[state] && ( isObject$1(obj[state]) ? obj[state].hasOwnProperty(visualType) : obj[state] === visualType // e.g., inRange: 'symbol' ); } VisualMapModel.prototype.completeVisualOption.apply(this, arguments); }, _resetSelected: function (newOption, isInit) { var thisOption = this.option; var pieceList = this._pieceList; // Selected do not merge but all override. var selected = (isInit ? thisOption : newOption).selected || {}; thisOption.selected = selected; // Consider 'not specified' means true. each$1(pieceList, function (piece, index) { var key = this.getSelectedMapKey(piece); if (!selected.hasOwnProperty(key)) { selected[key] = true; } }, this); if (thisOption.selectedMode === 'single') { // Ensure there is only one selected. var hasSel = false; each$1(pieceList, function (piece, index) { var key = this.getSelectedMapKey(piece); if (selected[key]) { hasSel ? (selected[key] = false) : (hasSel = true); } }, this); } // thisOption.selectedMode === 'multiple', default: all selected. }, /** * @public */ getSelectedMapKey: function (piece) { return this._mode === 'categories' ? piece.value + '' : piece.index + ''; }, /** * @public */ getPieceList: function () { return this._pieceList; }, /** * @private * @return {string} */ _determineMode: function () { var option = this.option; return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber'; }, /** * @public * @override */ setSelected: function (selected) { this.option.selected = clone(selected); }, /** * @public * @override */ getValueState: function (value) { var index = VisualMapping.findPieceIndex(value, this._pieceList); return index != null ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' ) : 'outOfRange'; }, /** * @public * @params {number} pieceIndex piece index in visualMapModel.getPieceList() * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...] */ findTargetDataIndices: function (pieceIndex) { var result = []; this.eachTargetSeries(function (seriesModel) { var dataIndices = []; var data = seriesModel.getData(); data.each(this.getDataDimension(data), function (value, dataIndex) { // Should always base on model pieceList, because it is order sensitive. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList); pIdx === pieceIndex && dataIndices.push(dataIndex); }, this); result.push({seriesId: seriesModel.id, dataIndex: dataIndices}); }, this); return result; }, /** * @private * @param {Object} piece piece.value or piece.interval is required. * @return {number} Can be Infinity or -Infinity */ getRepresentValue: function (piece) { var representValue; if (this.isCategory()) { representValue = piece.value; } else { if (piece.value != null) { representValue = piece.value; } else { var pieceInterval = piece.interval || []; representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity) ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2; } } return representValue; }, getVisualMeta: function (getColorVisual) { // Do not support category. (category axis is ordinal, numerical) if (this.isCategory()) { return; } var stops = []; var outerColors = []; var visualMapModel = this; function setStop(interval, valueState) { var representValue = visualMapModel.getRepresentValue({interval: interval}); if (!valueState) { valueState = visualMapModel.getValueState(representValue); } var color = getColorVisual(representValue, valueState); if (interval[0] === -Infinity) { outerColors[0] = color; } else if (interval[1] === Infinity) { outerColors[1] = color; } else { stops.push( {value: interval[0], color: color}, {value: interval[1], color: color} ); } } // Suplement var pieceList = this._pieceList.slice(); if (!pieceList.length) { pieceList.push({interval: [-Infinity, Infinity]}); } else { var edge = pieceList[0].interval[0]; edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]}); edge = pieceList[pieceList.length - 1].interval[1]; edge !== Infinity && pieceList.push({interval: [edge, Infinity]}); } var curr = -Infinity; each$1(pieceList, function (piece) { var interval = piece.interval; if (interval) { // Fulfill gap. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange'); setStop(interval.slice()); curr = interval[1]; } }, this); return {stops: stops, outerColors: outerColors}; } }); /** * Key is this._mode * @type {Object} * @this {module:echarts/component/viusalMap/PiecewiseMode} */ var resetMethods = { splitNumber: function () { var thisOption = this.option; var pieceList = this._pieceList; var precision = Math.min(thisOption.precision, 20); var dataExtent = this.getExtent(); var splitNumber = thisOption.splitNumber; splitNumber = Math.max(parseInt(splitNumber, 10), 1); thisOption.splitNumber = splitNumber; var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption while (+splitStep.toFixed(precision) !== splitStep && precision < 5) { precision++; } thisOption.precision = precision; splitStep = +splitStep.toFixed(precision); var index = 0; if (thisOption.minOpen) { pieceList.push({ index: index++, interval: [-Infinity, dataExtent[0]], close: [0, 0] }); } for ( var curr = dataExtent[0], len = index + splitNumber; index < len; curr += splitStep ) { var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep); pieceList.push({ index: index++, interval: [curr, max], close: [1, 1] }); } if (thisOption.maxOpen) { pieceList.push({ index: index++, interval: [dataExtent[1], Infinity], close: [0, 0] }); } reformIntervals(pieceList); each$1(pieceList, function (piece) { piece.text = this.formatValueText(piece.interval); }, this); }, categories: function () { var thisOption = this.option; each$1(thisOption.categories, function (cate) { // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。 // 是否改一致。 this._pieceList.push({ text: this.formatValueText(cate, true), value: cate }); }, this); // See "Order Rule". normalizeReverse(thisOption, this._pieceList); }, pieces: function () { var thisOption = this.option; var pieceList = this._pieceList; each$1(thisOption.pieces, function (pieceListItem, index) { if (!isObject$1(pieceListItem)) { pieceListItem = {value: pieceListItem}; } var item = {text: '', index: index}; if (pieceListItem.label != null) { item.text = pieceListItem.label; } if (pieceListItem.hasOwnProperty('value')) { var value = item.value = pieceListItem.value; item.interval = [value, value]; item.close = [1, 1]; } else { // `min` `max` is legacy option. // `lt` `gt` `lte` `gte` is recommanded. var interval = item.interval = []; var close = item.close = [0, 0]; var closeList = [1, 0, 1]; var infinityList = [-Infinity, Infinity]; var useMinMax = []; for (var lg = 0; lg < 2; lg++) { var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg]; for (var i = 0; i < 3 && interval[lg] == null; i++) { interval[lg] = pieceListItem[names[i]]; close[lg] = closeList[i]; useMinMax[lg] = i === 2; } interval[lg] == null && (interval[lg] = infinityList[lg]); } useMinMax[0] && interval[1] === Infinity && (close[0] = 0); useMinMax[1] && interval[0] === -Infinity && (close[1] = 0); if (__DEV__) { if (interval[0] > interval[1]) { console.warn( 'Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.' ); } } if (interval[0] === interval[1] && close[0] && close[1]) { // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}], // we use value to lift the priority when min === max item.value = interval[0]; } } item.visual = VisualMapping.retrieveVisuals(pieceListItem); pieceList.push(item); }, this); // See "Order Rule". normalizeReverse(thisOption, pieceList); // Only pieces reformIntervals(pieceList); each$1(pieceList, function (piece) { var close = piece.close; var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]]; piece.text = piece.text || this.formatValueText( piece.value != null ? piece.value : piece.interval, false, edgeSymbols ); }, this); } }; function normalizeReverse(thisOption, pieceList) { var inverse = thisOption.inverse; if (thisOption.orient === 'vertical' ? !inverse : inverse) { pieceList.reverse(); } } var PiecewiseVisualMapView = VisualMapView.extend({ type: 'visualMap.piecewise', /** * @protected * @override */ doRender: function () { var thisGroup = this.group; thisGroup.removeAll(); var visualMapModel = this.visualMapModel; var textGap = visualMapModel.get('textGap'); var textStyleModel = visualMapModel.textStyleModel; var textFont = textStyleModel.getFont(); var textFill = textStyleModel.getTextColor(); var itemAlign = this._getItemAlign(); var itemSize = visualMapModel.itemSize; var viewData = this._getViewData(); var endsText = viewData.endsText; var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText); endsText && this._renderEndsText( thisGroup, endsText[0], itemSize, showLabel, itemAlign ); each$1(viewData.viewPieceList, renderItem, this); endsText && this._renderEndsText( thisGroup, endsText[1], itemSize, showLabel, itemAlign ); box( visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap') ); this.renderBackground(thisGroup); this.positionGroup(thisGroup); function renderItem(item) { var piece = item.piece; var itemGroup = new Group(); itemGroup.onclick = bind(this._onItemClick, this, piece); this._enableHoverLink(itemGroup, item.indexInModelPieceList); var representValue = visualMapModel.getRepresentValue(piece); this._createItemSymbol( itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]] ); if (showLabel) { var visualState = this.visualMapModel.getValueState(representValue); itemGroup.add(new Text({ style: { x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap, y: itemSize[1] / 2, text: piece.text, textVerticalAlign: 'middle', textAlign: itemAlign, textFont: textFont, textFill: textFill, opacity: visualState === 'outOfRange' ? 0.5 : 1 } })); } thisGroup.add(itemGroup); } }, /** * @private */ _enableHoverLink: function (itemGroup, pieceIndex) { itemGroup .on('mouseover', bind(onHoverLink, this, 'highlight')) .on('mouseout', bind(onHoverLink, this, 'downplay')); function onHoverLink(method) { var visualMapModel = this.visualMapModel; visualMapModel.option.hoverLink && this.api.dispatchAction({ type: method, batch: convertDataIndex( visualMapModel.findTargetDataIndices(pieceIndex) ) }); } }, /** * @private */ _getItemAlign: function () { var visualMapModel = this.visualMapModel; var modelOption = visualMapModel.option; if (modelOption.orient === 'vertical') { return getItemAlign( visualMapModel, this.api, visualMapModel.itemSize ); } else { // horizontal, most case left unless specifying right. var align = modelOption.align; if (!align || align === 'auto') { align = 'left'; } return align; } }, /** * @private */ _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) { if (!text) { return; } var itemGroup = new Group(); var textStyleModel = this.visualMapModel.textStyleModel; itemGroup.add(new Text({ style: { x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2, y: itemSize[1] / 2, textVerticalAlign: 'middle', textAlign: showLabel ? itemAlign : 'center', text: text, textFont: textStyleModel.getFont(), textFill: textStyleModel.getTextColor() } })); group.add(itemGroup); }, /** * @private * @return {Object} {peiceList, endsText} The order is the same as screen pixel order. */ _getViewData: function () { var visualMapModel = this.visualMapModel; var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) { return {piece: piece, indexInModelPieceList: index}; }); var endsText = visualMapModel.get('text'); // Consider orient and inverse. var orient = visualMapModel.get('orient'); var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high] if (orient === 'horizontal' ? inverse : !inverse) { viewPieceList.reverse(); } // Origin order of endsText is [high, low] else if (endsText) { endsText = endsText.slice().reverse(); } return {viewPieceList: viewPieceList, endsText: endsText}; }, /** * @private */ _createItemSymbol: function (group, representValue, shapeParam) { group.add(createSymbol( this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], this.getControllerVisual(representValue, 'color') )); }, /** * @private */ _onItemClick: function (piece) { var visualMapModel = this.visualMapModel; var option = visualMapModel.option; var selected = clone(option.selected); var newKey = visualMapModel.getSelectedMapKey(piece); if (option.selectedMode === 'single') { selected[newKey] = true; each$1(selected, function (o, key) { selected[key] = key === newKey; }); } else { selected[newKey] = !selected[newKey]; } this.api.dispatchAction({ type: 'selectDataRange', from: this.uid, visualMapId: this.visualMapModel.id, selected: selected }); } }); /** * DataZoom component entry */ registerPreprocessor(preprocessor$2); /** * visualMap component entry */ var addCommas$1 = addCommas; var encodeHTML$1 = encodeHTML; function fillLabel(opt) { defaultEmphasis(opt, 'label', ['show']); } var MarkerModel = extendComponentModel({ type: 'marker', dependencies: ['series', 'grid', 'polar', 'geo'], /** * @overrite */ init: function (option, parentModel, ecModel, extraOpt) { if (__DEV__) { if (this.type === 'marker') { throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.'); } } this.mergeDefaultAndTheme(option, ecModel); this.mergeOption(option, ecModel, extraOpt.createdBySelf, true); }, /** * @return {boolean} */ isAnimationEnabled: function () { if (env$1.node) { return false; } var hostSeries = this.__hostSeries; return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled(); }, mergeOption: function (newOpt, ecModel, createdBySelf, isInit) { var MarkerModel = this.constructor; var modelPropName = this.mainType + 'Model'; if (!createdBySelf) { ecModel.eachSeries(function (seriesModel) { var markerOpt = seriesModel.get(this.mainType); var markerModel = seriesModel[modelPropName]; if (!markerOpt || !markerOpt.data) { seriesModel[modelPropName] = null; return; } if (!markerModel) { if (isInit) { // Default label emphasis `position` and `show` fillLabel(markerOpt); } each$1(markerOpt.data, function (item) { // FIXME Overwrite fillLabel method ? if (item instanceof Array) { fillLabel(item[0]); fillLabel(item[1]); } else { fillLabel(item); } }); markerModel = new MarkerModel( markerOpt, this, ecModel ); extend(markerModel, { mainType: this.mainType, // Use the same series index and name seriesIndex: seriesModel.seriesIndex, name: seriesModel.name, createdBySelf: true }); markerModel.__hostSeries = seriesModel; } else { markerModel.mergeOption(markerOpt, ecModel, true); } seriesModel[modelPropName] = markerModel; }, this); } }, formatTooltip: function (dataIndex) { var data = this.getData(); var value = this.getRawValue(dataIndex); var formattedValue = isArray(value) ? map(value, addCommas$1).join(', ') : addCommas$1(value); var name = data.getName(dataIndex); var html = encodeHTML$1(this.name); if (value != null || name) { html += '<br />'; } if (name) { html += encodeHTML$1(name); if (value != null) { html += ' : '; } } if (value != null) { html += encodeHTML$1(formattedValue); } return html; }, getData: function () { return this._data; }, setData: function (data) { this._data = data; } }); mixin(MarkerModel, dataFormatMixin); MarkerModel.extend({ type: 'markPoint', defaultOption: { zlevel: 0, z: 5, symbol: 'pin', symbolSize: 50, //symbolRotate: 0, //symbolOffset: [0, 0] tooltip: { trigger: 'item' }, label: { show: true, position: 'inside' }, itemStyle: { borderWidth: 2 }, emphasis: { label: { show: true } } } }); var indexOf$2 = indexOf; function hasXOrY(item) { return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y))); } function hasXAndY(item) { return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y)); } // Make it simple, do not visit all stacked value to count precision. // function getPrecision(data, valueAxisDim, dataIndex) { // var precision = -1; // var stackedDim = data.mapDimension(valueAxisDim); // do { // precision = Math.max( // numberUtil.getPrecision(data.get(stackedDim, dataIndex)), // precision // ); // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries'); // if (stackedOnSeries) { // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex); // data = stackedOnSeries.getData(); // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue); // stackedDim = data.getCalculationInfo('stackedDimension'); // } // else { // data = null; // } // } while (data); // return precision; // } function markerTypeCalculatorWithExtent( mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex ) { var coordArr = []; var stacked = isDimensionStacked(data, targetDataDim, otherDataDim); var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim; var value = numCalculate(data, calcDataDim, mlType); var dataIndex = data.indicesOfNearest(calcDataDim, value)[0]; coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex); coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision. var precision = getPrecision(data.get(targetDataDim, dataIndex)); precision = Math.min(precision, 20); if (precision >= 0) { coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision); } return coordArr; } var curry$7 = curry; // TODO Specified percent var markerTypeCalculator = { /** * @method * @param {module:echarts/data/List} data * @param {string} baseAxisDim * @param {string} valueAxisDim */ min: curry$7(markerTypeCalculatorWithExtent, 'min'), /** * @method * @param {module:echarts/data/List} data * @param {string} baseAxisDim * @param {string} valueAxisDim */ max: curry$7(markerTypeCalculatorWithExtent, 'max'), /** * @method * @param {module:echarts/data/List} data * @param {string} baseAxisDim * @param {string} valueAxisDim */ average: curry$7(markerTypeCalculatorWithExtent, 'average') }; /** * Transform markPoint data item to format used in List by do the following * 1. Calculate statistic like `max`, `min`, `average` * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/coord/*} [coordSys] * @param {Object} item * @return {Object} */ function dataTransform(seriesModel, item) { var data = seriesModel.getData(); var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly // 2. If `coord` is not a data array. Which uses `xAxis`, // `yAxis` to specify the coord on each dimension // parseFloat first because item.x and item.y can be percent string like '20%' if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) { var dims = coordSys.dimensions; var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value item = clone(item); if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis ) { var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim); var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim); item.coord = markerTypeCalculator[item.type]( data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex ); // Force to use the value of calculated value. item.value = item.coord[targetCoordIndex]; } else { // FIXME Only has one of xAxis and yAxis. var coord = [ item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis ]; // Each coord support max, min, average for (var i = 0; i < 2; i++) { if (markerTypeCalculator[coord[i]]) { coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]); } } item.coord = coord; } } return item; } function getAxisInfo$1(item, data, coordSys, seriesModel) { var ret = {}; if (item.valueIndex != null || item.valueDim != null) { ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim; ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim)); ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis); ret.baseDataDim = data.mapDimension(ret.baseAxis.dim); } else { ret.baseAxis = seriesModel.getBaseAxis(); ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis); ret.baseDataDim = data.mapDimension(ret.baseAxis.dim); ret.valueDataDim = data.mapDimension(ret.valueAxis.dim); } return ret; } function dataDimToCoordDim(seriesModel, dataDim) { var data = seriesModel.getData(); var dimensions = data.dimensions; dataDim = data.getDimension(dataDim); for (var i = 0; i < dimensions.length; i++) { var dimItem = data.getDimensionInfo(dimensions[i]); if (dimItem.name === dataDim) { return dimItem.coordDim; } } } /** * Filter data which is out of coordinateSystem range * [dataFilter description] * @param {module:echarts/coord/*} [coordSys] * @param {Object} item * @return {boolean} */ function dataFilter$1(coordSys, item) { // Alwalys return true if there is no coordSys return (coordSys && coordSys.containData && item.coord && !hasXOrY(item)) ? coordSys.containData(item.coord) : true; } function dimValueGetter(item, dimName, dataIndex, dimIndex) { // x, y, radius, angle if (dimIndex < 2) { return item.coord && item.coord[dimIndex]; } return item.value; } function numCalculate(data, valueDataDim, type) { if (type === 'average') { var sum = 0; var count = 0; data.each(valueDataDim, function (val, idx) { if (!isNaN(val)) { sum += val; count++; } }); return sum / count; } else { return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0]; } } var MarkerView = extendComponentView({ type: 'marker', init: function () { /** * Markline grouped by series * @private * @type {module:zrender/core/util.HashMap} */ this.markerGroupMap = createHashMap(); }, render: function (markerModel, ecModel, api) { var markerGroupMap = this.markerGroupMap; markerGroupMap.each(function (item) { item.__keep = false; }); var markerModelKey = this.type + 'Model'; ecModel.eachSeries(function (seriesModel) { var markerModel = seriesModel[markerModelKey]; markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api); }, this); markerGroupMap.each(function (item) { !item.__keep && this.group.remove(item.group); }, this); }, renderSeries: function () {} }); function updateMarkerLayout(mpData, seriesModel, api) { var coordSys = seriesModel.coordinateSystem; mpData.each(function (idx) { var itemModel = mpData.getItemModel(idx); var point; var xPx = parsePercent$1(itemModel.get('x'), api.getWidth()); var yPx = parsePercent$1(itemModel.get('y'), api.getHeight()); if (!isNaN(xPx) && !isNaN(yPx)) { point = [xPx, yPx]; } // Chart like bar may have there own marker positioning logic else if (seriesModel.getMarkerPosition) { // Use the getMarkerPoisition point = seriesModel.getMarkerPosition( mpData.getValues(mpData.dimensions, idx) ); } else if (coordSys) { var x = mpData.get(coordSys.dimensions[0], idx); var y = mpData.get(coordSys.dimensions[1], idx); point = coordSys.dataToPoint([x, y]); } // Use x, y if has any if (!isNaN(xPx)) { point[0] = xPx; } if (!isNaN(yPx)) { point[1] = yPx; } mpData.setItemLayout(idx, point); }); } MarkerView.extend({ type: 'markPoint', // updateLayout: function (markPointModel, ecModel, api) { // ecModel.eachSeries(function (seriesModel) { // var mpModel = seriesModel.markPointModel; // if (mpModel) { // updateMarkerLayout(mpModel.getData(), seriesModel, api); // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel); // } // }, this); // }, updateTransform: function (markPointModel, ecModel, api) { ecModel.eachSeries(function (seriesModel) { var mpModel = seriesModel.markPointModel; if (mpModel) { updateMarkerLayout(mpModel.getData(), seriesModel, api); this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel); } }, this); }, renderSeries: function (seriesModel, mpModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var seriesId = seriesModel.id; var seriesData = seriesModel.getData(); var symbolDrawMap = this.markerGroupMap; var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw()); var mpData = createList$1(coordSys, seriesModel, mpModel); // FIXME mpModel.setData(mpData); updateMarkerLayout(mpModel.getData(), seriesModel, api); mpData.each(function (idx) { var itemModel = mpData.getItemModel(idx); var symbolSize = itemModel.getShallow('symbolSize'); if (typeof symbolSize === 'function') { // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据? symbolSize = symbolSize( mpModel.getRawValue(idx), mpModel.getDataParams(idx) ); } mpData.setItemVisual(idx, { symbolSize: symbolSize, color: itemModel.get('itemStyle.color') || seriesData.getVisual('color'), symbol: itemModel.getShallow('symbol') }); }); // TODO Text are wrong symbolDraw.updateData(mpData); this.group.add(symbolDraw.group); // Set host model for tooltip // FIXME mpData.eachItemGraphicEl(function (el) { el.traverse(function (child) { child.dataModel = mpModel; }); }); symbolDraw.__keep = true; symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent'); } }); /** * @inner * @param {module:echarts/coord/*} [coordSys] * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Model} mpModel */ function createList$1(coordSys, seriesModel, mpModel) { var coordDimsInfos; if (coordSys) { coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) { var info = seriesModel.getData().getDimensionInfo( seriesModel.getData().mapDimension(coordDim) ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys return defaults({name: coordDim}, info); }); } else { coordDimsInfos =[{ name: 'value', type: 'float' }]; } var mpData = new List(coordDimsInfos, mpModel); var dataOpt = map(mpModel.get('data'), curry( dataTransform, seriesModel )); if (coordSys) { dataOpt = filter( dataOpt, curry(dataFilter$1, coordSys) ); } mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function (item) { return item.value; } ); return mpData; } // HINT Markpoint can't be used too much registerPreprocessor(function (opt) { // Make sure markPoint component is enabled opt.markPoint = opt.markPoint || {}; }); MarkerModel.extend({ type: 'markLine', defaultOption: { zlevel: 0, z: 5, symbol: ['circle', 'arrow'], symbolSize: [8, 16], //symbolRotate: 0, precision: 2, tooltip: { trigger: 'item' }, label: { show: true, position: 'end' }, lineStyle: { type: 'dashed' }, emphasis: { label: { show: true }, lineStyle: { width: 3 } }, animationEasing: 'linear' } }); var markLineTransform = function (seriesModel, coordSys, mlModel, item) { var data = seriesModel.getData(); // Special type markLine like 'min', 'max', 'average' var mlType = item.type; if (!isArray(item) && ( mlType === 'min' || mlType === 'max' || mlType === 'average' // In case // data: [{ // yAxis: 10 // }] || (item.xAxis != null || item.yAxis != null) ) ) { var valueAxis; var valueDataDim; var value; if (item.yAxis != null || item.xAxis != null) { valueDataDim = item.yAxis != null ? 'y' : 'x'; valueAxis = coordSys.getAxis(valueDataDim); value = retrieve(item.yAxis, item.xAxis); } else { var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); valueDataDim = axisInfo.valueDataDim; valueAxis = axisInfo.valueAxis; value = numCalculate(data, valueDataDim, mlType); } var valueIndex = valueDataDim === 'x' ? 0 : 1; var baseIndex = 1 - valueIndex; var mlFrom = clone(item); var mlTo = {}; mlFrom.type = null; mlFrom.coord = []; mlTo.coord = []; mlFrom.coord[baseIndex] = -Infinity; mlTo.coord[baseIndex] = Infinity; var precision = mlModel.get('precision'); if (precision >= 0 && typeof value === 'number') { value = +value.toFixed(Math.min(precision, 20)); } mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value; item = [mlFrom, mlTo, { // Extra option for tooltip and label type: mlType, valueIndex: item.valueIndex, // Force to use the value of calculated value. value: value }]; } item = [ dataTransform(seriesModel, item[0]), dataTransform(seriesModel, item[1]), extend({}, item[2]) ]; // Avoid line data type is extended by from(to) data type item[2].type = item[2].type || ''; // Merge from option and to option into line option merge(item[2], item[0]); merge(item[2], item[1]); return item; }; function isInifinity(val) { return !isNaN(val) && !isFinite(val); } // If a markLine has one dim function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) { var otherDimIndex = 1 - dimIndex; var dimName = coordSys.dimensions[dimIndex]; return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]); } function markLineFilter(coordSys, item) { if (coordSys.type === 'cartesian2d') { var fromCoord = item[0].coord; var toCoord = item[1].coord; // In case // { // markLine: { // data: [{ yAxis: 2 }] // } // } if ( fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys)) ) { return true; } } return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]); } function updateSingleMarkerEndLayout( data, idx, isFrom, seriesModel, api ) { var coordSys = seriesModel.coordinateSystem; var itemModel = data.getItemModel(idx); var point; var xPx = parsePercent$1(itemModel.get('x'), api.getWidth()); var yPx = parsePercent$1(itemModel.get('y'), api.getHeight()); if (!isNaN(xPx) && !isNaN(yPx)) { point = [xPx, yPx]; } else { // Chart like bar may have there own marker positioning logic if (seriesModel.getMarkerPosition) { // Use the getMarkerPoisition point = seriesModel.getMarkerPosition( data.getValues(data.dimensions, idx) ); } else { var dims = coordSys.dimensions; var x = data.get(dims[0], idx); var y = data.get(dims[1], idx); point = coordSys.dataToPoint([x, y]); } // Expand line to the edge of grid if value on one axis is Inifnity // In case // markLine: { // data: [{ // yAxis: 2 // // or // type: 'average' // }] // } if (coordSys.type === 'cartesian2d') { var xAxis = coordSys.getAxis('x'); var yAxis = coordSys.getAxis('y'); var dims = coordSys.dimensions; if (isInifinity(data.get(dims[0], idx))) { point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]); } else if (isInifinity(data.get(dims[1], idx))) { point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]); } } // Use x, y if has any if (!isNaN(xPx)) { point[0] = xPx; } if (!isNaN(yPx)) { point[1] = yPx; } } data.setItemLayout(idx, point); } MarkerView.extend({ type: 'markLine', // updateLayout: function (markLineModel, ecModel, api) { // ecModel.eachSeries(function (seriesModel) { // var mlModel = seriesModel.markLineModel; // if (mlModel) { // var mlData = mlModel.getData(); // var fromData = mlModel.__from; // var toData = mlModel.__to; // // Update visual and layout of from symbol and to symbol // fromData.each(function (idx) { // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api); // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api); // }); // // Update layout of line // mlData.each(function (idx) { // mlData.setItemLayout(idx, [ // fromData.getItemLayout(idx), // toData.getItemLayout(idx) // ]); // }); // this.markerGroupMap.get(seriesModel.id).updateLayout(); // } // }, this); // }, updateTransform: function (markLineModel, ecModel, api) { ecModel.eachSeries(function (seriesModel) { var mlModel = seriesModel.markLineModel; if (mlModel) { var mlData = mlModel.getData(); var fromData = mlModel.__from; var toData = mlModel.__to; // Update visual and layout of from symbol and to symbol fromData.each(function (idx) { updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api); updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api); }); // Update layout of line mlData.each(function (idx) { mlData.setItemLayout(idx, [ fromData.getItemLayout(idx), toData.getItemLayout(idx) ]); }); this.markerGroupMap.get(seriesModel.id).updateLayout(); } }, this); }, renderSeries: function (seriesModel, mlModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var seriesId = seriesModel.id; var seriesData = seriesModel.getData(); var lineDrawMap = this.markerGroupMap; var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw()); this.group.add(lineDraw.group); var mlData = createList$2(coordSys, seriesModel, mlModel); var fromData = mlData.from; var toData = mlData.to; var lineData = mlData.line; mlModel.__from = fromData; mlModel.__to = toData; // Line data for tooltip and formatter mlModel.setData(lineData); var symbolType = mlModel.get('symbol'); var symbolSize = mlModel.get('symbolSize'); if (!isArray(symbolType)) { symbolType = [symbolType, symbolType]; } if (typeof symbolSize === 'number') { symbolSize = [symbolSize, symbolSize]; } // Update visual and layout of from symbol and to symbol mlData.from.each(function (idx) { updateDataVisualAndLayout(fromData, idx, true); updateDataVisualAndLayout(toData, idx, false); }); // Update visual and layout of line lineData.each(function (idx) { var lineColor = lineData.getItemModel(idx).get('lineStyle.color'); lineData.setItemVisual(idx, { color: lineColor || fromData.getItemVisual(idx, 'color') }); lineData.setItemLayout(idx, [ fromData.getItemLayout(idx), toData.getItemLayout(idx) ]); lineData.setItemVisual(idx, { 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'), 'fromSymbol': fromData.getItemVisual(idx, 'symbol'), 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'), 'toSymbol': toData.getItemVisual(idx, 'symbol') }); }); lineDraw.updateData(lineData); // Set host model for tooltip // FIXME mlData.line.eachItemGraphicEl(function (el, idx) { el.traverse(function (child) { child.dataModel = mlModel; }); }); function updateDataVisualAndLayout(data, idx, isFrom) { var itemModel = data.getItemModel(idx); updateSingleMarkerEndLayout( data, idx, isFrom, seriesModel, api ); data.setItemVisual(idx, { symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1], symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1], color: itemModel.get('itemStyle.color') || seriesData.getVisual('color') }); } lineDraw.__keep = true; lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent'); } }); /** * @inner * @param {module:echarts/coord/*} coordSys * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Model} mpModel */ function createList$2(coordSys, seriesModel, mlModel) { var coordDimsInfos; if (coordSys) { coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) { var info = seriesModel.getData().getDimensionInfo( seriesModel.getData().mapDimension(coordDim) ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys return defaults({name: coordDim}, info); }); } else { coordDimsInfos =[{ name: 'value', type: 'float' }]; } var fromData = new List(coordDimsInfos, mlModel); var toData = new List(coordDimsInfos, mlModel); // No dimensions var lineData = new List([], mlModel); var optData = map(mlModel.get('data'), curry( markLineTransform, seriesModel, coordSys, mlModel )); if (coordSys) { optData = filter( optData, curry(markLineFilter, coordSys) ); } var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) { return item.value; }; fromData.initData( map(optData, function (item) { return item[0]; }), null, dimValueGetter$$1 ); toData.initData( map(optData, function (item) { return item[1]; }), null, dimValueGetter$$1 ); lineData.initData( map(optData, function (item) { return item[2]; }) ); lineData.hasItemOption = true; return { from: fromData, to: toData, line: lineData }; } registerPreprocessor(function (opt) { // Make sure markLine component is enabled opt.markLine = opt.markLine || {}; }); MarkerModel.extend({ type: 'markArea', defaultOption: { zlevel: 0, // PENDING z: 1, tooltip: { trigger: 'item' }, // markArea should fixed on the coordinate system animation: false, label: { show: true, position: 'top' }, itemStyle: { // color and borderColor default to use color from series // color: 'auto' // borderColor: 'auto' borderWidth: 0 }, emphasis: { label: { show: true, position: 'top' } } } }); // TODO Better on polar var markAreaTransform = function (seriesModel, coordSys, maModel, item) { var lt = dataTransform(seriesModel, item[0]); var rb = dataTransform(seriesModel, item[1]); var retrieve$$1 = retrieve; // FIXME make sure lt is less than rb var ltCoord = lt.coord; var rbCoord = rb.coord; ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity); ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity); rbCoord[0] = retrieve$$1(rbCoord[0], Infinity); rbCoord[1] = retrieve$$1(rbCoord[1], Infinity); // Merge option into one var result = mergeAll([{}, lt, rb]); result.coord = [ lt.coord, rb.coord ]; result.x0 = lt.x; result.y0 = lt.y; result.x1 = rb.x; result.y1 = rb.y; return result; }; function isInifinity$1(val) { return !isNaN(val) && !isFinite(val); } // If a markArea has one dim function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) { var otherDimIndex = 1 - dimIndex; return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]); } function markAreaFilter(coordSys, item) { var fromCoord = item.coord[0]; var toCoord = item.coord[1]; if (coordSys.type === 'cartesian2d') { // In case // { // markArea: { // data: [{ yAxis: 2 }] // } // } if ( fromCoord && toCoord && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys)) ) { return true; } } return dataFilter$1(coordSys, { coord: fromCoord, x: item.x0, y: item.y0 }) || dataFilter$1(coordSys, { coord: toCoord, x: item.x1, y: item.y1 }); } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0'] function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) { var coordSys = seriesModel.coordinateSystem; var itemModel = data.getItemModel(idx); var point; var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth()); var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight()); if (!isNaN(xPx) && !isNaN(yPx)) { point = [xPx, yPx]; } else { // Chart like bar may have there own marker positioning logic if (seriesModel.getMarkerPosition) { // Use the getMarkerPoisition point = seriesModel.getMarkerPosition( data.getValues(dims, idx) ); } else { var x = data.get(dims[0], idx); var y = data.get(dims[1], idx); var pt = [x, y]; coordSys.clampData && coordSys.clampData(pt, pt); point = coordSys.dataToPoint(pt, true); } if (coordSys.type === 'cartesian2d') { var xAxis = coordSys.getAxis('x'); var yAxis = coordSys.getAxis('y'); var x = data.get(dims[0], idx); var y = data.get(dims[1], idx); if (isInifinity$1(x)) { point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]); } else if (isInifinity$1(y)) { point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]); } } // Use x, y if has any if (!isNaN(xPx)) { point[0] = xPx; } if (!isNaN(yPx)) { point[1] = yPx; } } return point; } var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']]; MarkerView.extend({ type: 'markArea', // updateLayout: function (markAreaModel, ecModel, api) { // ecModel.eachSeries(function (seriesModel) { // var maModel = seriesModel.markAreaModel; // if (maModel) { // var areaData = maModel.getData(); // areaData.each(function (idx) { // var points = zrUtil.map(dimPermutations, function (dim) { // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api); // }); // // Layout // areaData.setItemLayout(idx, points); // var el = areaData.getItemGraphicEl(idx); // el.setShape('points', points); // }); // } // }, this); // }, updateTransform: function (markAreaModel, ecModel, api) { ecModel.eachSeries(function (seriesModel) { var maModel = seriesModel.markAreaModel; if (maModel) { var areaData = maModel.getData(); areaData.each(function (idx) { var points = map(dimPermutations, function (dim) { return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api); }); // Layout areaData.setItemLayout(idx, points); var el = areaData.getItemGraphicEl(idx); el.setShape('points', points); }); } }, this); }, renderSeries: function (seriesModel, maModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var seriesName = seriesModel.name; var seriesData = seriesModel.getData(); var areaGroupMap = this.markerGroupMap; var polygonGroup = areaGroupMap.get(seriesName) || areaGroupMap.set(seriesName, {group: new Group()}); this.group.add(polygonGroup.group); polygonGroup.__keep = true; var areaData = createList$3(coordSys, seriesModel, maModel); // Line data for tooltip and formatter maModel.setData(areaData); // Update visual and layout of line areaData.each(function (idx) { // Layout areaData.setItemLayout(idx, map(dimPermutations, function (dim) { return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api); })); // Visual areaData.setItemVisual(idx, { color: seriesData.getVisual('color') }); }); areaData.diff(polygonGroup.__data) .add(function (idx) { var polygon = new Polygon({ shape: { points: areaData.getItemLayout(idx) } }); areaData.setItemGraphicEl(idx, polygon); polygonGroup.group.add(polygon); }) .update(function (newIdx, oldIdx) { var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx); updateProps(polygon, { shape: { points: areaData.getItemLayout(newIdx) } }, maModel, newIdx); polygonGroup.group.add(polygon); areaData.setItemGraphicEl(newIdx, polygon); }) .remove(function (idx) { var polygon = polygonGroup.__data.getItemGraphicEl(idx); polygonGroup.group.remove(polygon); }) .execute(); areaData.eachItemGraphicEl(function (polygon, idx) { var itemModel = areaData.getItemModel(idx); var labelModel = itemModel.getModel('label'); var labelHoverModel = itemModel.getModel('emphasis.label'); var color = areaData.getItemVisual(idx, 'color'); polygon.useStyle( defaults( itemModel.getModel('itemStyle').getItemStyle(), { fill: modifyAlpha(color, 0.4), stroke: color } ) ); polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle(); setLabelStyle( polygon.style, polygon.hoverStyle, labelModel, labelHoverModel, { labelFetcher: maModel, labelDataIndex: idx, defaultText: areaData.getName(idx) || '', isRectText: true, autoColor: color } ); setHoverStyle(polygon, {}); polygon.dataModel = maModel; }); polygonGroup.__data = areaData; polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent'); } }); /** * @inner * @param {module:echarts/coord/*} coordSys * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Model} mpModel */ function createList$3(coordSys, seriesModel, maModel) { var coordDimsInfos; var areaData; var dims = ['x0', 'y0', 'x1', 'y1']; if (coordSys) { coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) { var data = seriesModel.getData(); var info = data.getDimensionInfo( data.mapDimension(coordDim) ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys return defaults({name: coordDim}, info); }); areaData = new List(map(dims, function (dim, idx) { return { name: dim, type: coordDimsInfos[idx % 2].type }; }), maModel); } else { coordDimsInfos =[{ name: 'value', type: 'float' }]; areaData = new List(coordDimsInfos, maModel); } var optData = map(maModel.get('data'), curry( markAreaTransform, seriesModel, coordSys, maModel )); if (coordSys) { optData = filter( optData, curry(markAreaFilter, coordSys) ); } var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) { return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2]; } : function (item) { return item.value; }; areaData.initData(optData, null, dimValueGetter$$1); areaData.hasItemOption = true; return areaData; } registerPreprocessor(function (opt) { // Make sure markArea component is enabled opt.markArea = opt.markArea || {}; }); var preprocessor$3 = function (option) { var timelineOpt = option && option.timeline; if (!isArray(timelineOpt)) { timelineOpt = timelineOpt ? [timelineOpt] : []; } each$1(timelineOpt, function (opt) { if (!opt) { return; } compatibleEC2(opt); }); }; function compatibleEC2(opt) { var type = opt.type; var ec2Types = {'number': 'value', 'time': 'time'}; // Compatible with ec2 if (ec2Types[type]) { opt.axisType = ec2Types[type]; delete opt.type; } transferItem(opt); if (has$2(opt, 'controlPosition')) { var controlStyle = opt.controlStyle || (opt.controlStyle = {}); if (!has$2(controlStyle, 'position')) { controlStyle.position = opt.controlPosition; } if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) { controlStyle.show = false; delete controlStyle.position; } delete opt.controlPosition; } each$1(opt.data || [], function (dataItem) { if (isObject$1(dataItem) && !isArray(dataItem)) { if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) { // In ec2, using name as value. dataItem.value = dataItem.name; } transferItem(dataItem); } }); } function transferItem(opt) { var itemStyle = opt.itemStyle || (opt.itemStyle = {}); var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out var label = opt.label || (opt.label || {}); var labelNormal = label.normal || (label.normal = {}); var excludeLabelAttr = {normal: 1, emphasis: 1}; each$1(label, function (value, name) { if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) { labelNormal[name] = value; } }); if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) { label.emphasis = itemStyleEmphasis.label; delete itemStyleEmphasis.label; } } function has$2(obj, attr) { return obj.hasOwnProperty(attr); } ComponentModel.registerSubTypeDefaulter('timeline', function () { // Only slider now. return 'slider'; }); registerAction( {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'}, function (payload, ecModel) { var timelineModel = ecModel.getComponent('timeline'); if (timelineModel && payload.currentIndex != null) { timelineModel.setCurrentIndex(payload.currentIndex); if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) { timelineModel.setPlayState(false); } } // Set normalized currentIndex to payload. ecModel.resetOption('timeline'); return defaults({ currentIndex: timelineModel.option.currentIndex }, payload); } ); registerAction( {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'}, function (payload, ecModel) { var timelineModel = ecModel.getComponent('timeline'); if (timelineModel && payload.playState != null) { timelineModel.setPlayState(payload.playState); } } ); var TimelineModel = ComponentModel.extend({ type: 'timeline', layoutMode: 'box', /** * @protected */ defaultOption: { zlevel: 0, // 一级层叠 z: 4, // 二级层叠 show: true, axisType: 'time', // 模式是时间类型,支持 value, category realtime: true, left: '20%', top: null, right: '20%', bottom: 0, width: null, height: 40, padding: 5, controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none' autoPlay: false, rewind: false, // 反向播放 loop: true, playInterval: 2000, // 播放时间间隔,单位ms currentIndex: 0, itemStyle: {}, label: { color: '#000' }, data: [] }, /** * @override */ init: function (option, parentModel, ecModel) { /** * @private * @type {module:echarts/data/List} */ this._data; /** * @private * @type {Array.<string>} */ this._names; this.mergeDefaultAndTheme(option, ecModel); this._initData(); }, /** * @override */ mergeOption: function (option) { TimelineModel.superApply(this, 'mergeOption', arguments); this._initData(); }, /** * @param {number} [currentIndex] */ setCurrentIndex: function (currentIndex) { if (currentIndex == null) { currentIndex = this.option.currentIndex; } var count = this._data.count(); if (this.option.loop) { currentIndex = (currentIndex % count + count) % count; } else { currentIndex >= count && (currentIndex = count - 1); currentIndex < 0 && (currentIndex = 0); } this.option.currentIndex = currentIndex; }, /** * @return {number} currentIndex */ getCurrentIndex: function () { return this.option.currentIndex; }, /** * @return {boolean} */ isIndexMax: function () { return this.getCurrentIndex() >= this._data.count() - 1; }, /** * @param {boolean} state true: play, false: stop */ setPlayState: function (state) { this.option.autoPlay = !!state; }, /** * @return {boolean} true: play, false: stop */ getPlayState: function () { return !!this.option.autoPlay; }, /** * @private */ _initData: function () { var thisOption = this.option; var dataArr = thisOption.data || []; var axisType = thisOption.axisType; var names = this._names = []; if (axisType === 'category') { var idxArr = []; each$1(dataArr, function (item, index) { var value = getDataItemValue(item); var newItem; if (isObject$1(item)) { newItem = clone(item); newItem.value = index; } else { newItem = index; } idxArr.push(newItem); if (!isString(value) && (value == null || isNaN(value))) { value = ''; } names.push(value + ''); }); dataArr = idxArr; } var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number'; var data = this._data = new List([{name: 'value', type: dimType}], this); data.initData(dataArr, names); }, getData: function () { return this._data; }, /** * @public * @return {Array.<string>} categoreis */ getCategories: function () { if (this.get('axisType') === 'category') { return this._names.slice(); } } }); var SliderTimelineModel = TimelineModel.extend({ type: 'timeline.slider', /** * @protected */ defaultOption: { backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色 borderColor: '#ccc', // 时间轴边框颜色 borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框) orient: 'horizontal', // 'vertical' inverse: false, tooltip: { // boolean or Object trigger: 'item' // data item may also have tootip attr. }, symbol: 'emptyCircle', symbolSize: 10, lineStyle: { show: true, width: 2, color: '#304654' }, label: { // 文本标签 position: 'auto', // auto left right top bottom // When using number, label position is not // restricted by viewRect. // positive: right/bottom, negative: left/top show: true, interval: 'auto', rotate: 0, // formatter: null, // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#304654' }, itemStyle: { color: '#304654', borderWidth: 1 }, checkpointStyle: { symbol: 'circle', symbolSize: 13, color: '#c23531', borderWidth: 5, borderColor: 'rgba(194,53,49, 0.5)', animation: true, animationDuration: 300, animationEasing: 'quinticInOut' }, controlStyle: { show: true, showPlayBtn: true, showPrevBtn: true, showNextBtn: true, itemSize: 22, itemGap: 12, position: 'left', // 'left' 'right' 'top' 'bottom' playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z', // jshint ignore:line stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z', // jshint ignore:line nextIcon: 'path://M18.6,50.8l22.5-22.5c0.2-0.2,0.3-0.4,0.3-0.7c0-0.3-0.1-0.5-0.3-0.7L18.7,4.4c-0.1-0.1-0.2-0.3-0.2-0.5 c0-0.4,0.3-0.8,0.8-0.8c0.2,0,0.5,0.1,0.6,0.3l23.5,23.5l0,0c0.2,0.2,0.3,0.4,0.3,0.7c0,0.3-0.1,0.5-0.3,0.7l-0.1,0.1L19.7,52 c-0.1,0.1-0.3,0.2-0.5,0.2c-0.4,0-0.8-0.3-0.8-0.8C18.4,51.2,18.5,51,18.6,50.8z', // jshint ignore:line prevIcon: 'path://M43,52.8L20.4,30.3c-0.2-0.2-0.3-0.4-0.3-0.7c0-0.3,0.1-0.5,0.3-0.7L42.9,6.4c0.1-0.1,0.2-0.3,0.2-0.5 c0-0.4-0.3-0.8-0.8-0.8c-0.2,0-0.5,0.1-0.6,0.3L18.3,28.8l0,0c-0.2,0.2-0.3,0.4-0.3,0.7c0,0.3,0.1,0.5,0.3,0.7l0.1,0.1L41.9,54 c0.1,0.1,0.3,0.2,0.5,0.2c0.4,0,0.8-0.3,0.8-0.8C43.2,53.2,43.1,53,43,52.8z', // jshint ignore:line color: '#304654', borderColor: '#304654', borderWidth: 1 }, emphasis: { label: { show: true, // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#c23531' }, itemStyle: { color: '#c23531' }, controlStyle: { color: '#c23531', borderColor: '#c23531', borderWidth: 2 } }, data: [] } }); mixin(SliderTimelineModel, dataFormatMixin); var TimelineView = Component.extend({ type: 'timeline' }); /** * 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 TimelineAxis = function (dim, scale, coordExtent, axisType) { Axis.call(this, dim, scale, coordExtent); /** * Axis type * - 'category' * - 'value' * - 'time' * - 'log' * @type {string} */ this.type = axisType || 'value'; /** * @private * @type {number} */ this._autoLabelInterval; /** * Axis model * @param {module:echarts/component/TimelineModel} */ this.model = null; }; TimelineAxis.prototype = { constructor: TimelineAxis, /** * @public * @return {number} */ getLabelInterval: function () { var timelineModel = this.model; var labelModel = timelineModel.getModel('label'); var labelInterval = labelModel.get('interval'); if (labelInterval != null && labelInterval != 'auto') { return labelInterval; } var labelInterval = this._autoLabelInterval; if (!labelInterval) { labelInterval = this._autoLabelInterval = getAxisLabelInterval( map(this.scale.getTicks(), this.dataToCoord, this), getFormattedLabels(this, labelModel.get('formatter')), labelModel.getFont(), timelineModel.get('orient') === 'horizontal' ? 0 : 90, labelModel.get('rotate') ); } return labelInterval; }, /** * If label is ignored. * Automatically used when axis is category and label can not be all shown * @public * @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); } } }; inherits(TimelineAxis, Axis); var bind$6 = bind; var each$28 = each$1; var PI$4 = Math.PI; TimelineView.extend({ type: 'timeline.slider', init: function (ecModel, api) { this.api = api; /** * @private * @type {module:echarts/component/timeline/TimelineAxis} */ this._axis; /** * @private * @type {module:zrender/core/BoundingRect} */ this._viewRect; /** * @type {number} */ this._timer; /** * @type {module:zrender/Element} */ this._currentPointer; /** * @type {module:zrender/container/Group} */ this._mainGroup; /** * @type {module:zrender/container/Group} */ this._labelGroup; }, /** * @override */ render: function (timelineModel, ecModel, api, payload) { this.model = timelineModel; this.api = api; this.ecModel = ecModel; this.group.removeAll(); if (timelineModel.get('show', true)) { var layoutInfo = this._layout(timelineModel, api); var mainGroup = this._createGroup('mainGroup'); var labelGroup = this._createGroup('labelGroup'); /** * @private * @type {module:echarts/component/timeline/TimelineAxis} */ var axis = this._axis = this._createAxis(layoutInfo, timelineModel); timelineModel.formatTooltip = function (dataIndex) { return encodeHTML(axis.scale.getLabel(dataIndex)); }; each$28( ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) { this['_render' + name](layoutInfo, mainGroup, axis, timelineModel); }, this ); this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel); this._position(layoutInfo, timelineModel); } this._doPlayStop(); }, /** * @override */ remove: function () { this._clearTimer(); this.group.removeAll(); }, /** * @override */ dispose: function () { this._clearTimer(); }, _layout: function (timelineModel, api) { var labelPosOpt = timelineModel.get('label.position'); var orient = timelineModel.get('orient'); var viewRect = getViewRect$4(timelineModel, api); // Auto label offset. if (labelPosOpt == null || labelPosOpt === 'auto') { labelPosOpt = orient === 'horizontal' ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+') : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-'); } else if (isNaN(labelPosOpt)) { labelPosOpt = ({ horizontal: {top: '-', bottom: '+'}, vertical: {left: '-', right: '+'} })[orient][labelPosOpt]; } var labelAlignMap = { horizontal: 'center', vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right' }; var labelBaselineMap = { horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom', vertical: 'middle' }; var rotationMap = { horizontal: 0, vertical: PI$4 / 2 }; // Position var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width; var controlModel = timelineModel.getModel('controlStyle'); var showControl = controlModel.get('show', true); var controlSize = showControl ? controlModel.get('itemSize') : 0; var controlGap = showControl ? controlModel.get('itemGap') : 0; var sizePlusGap = controlSize + controlGap; // Special label rotate. var labelRotation = timelineModel.get('label.rotate') || 0; labelRotation = labelRotation * PI$4 / 180; // To radian. var playPosition; var prevBtnPosition; var nextBtnPosition; var axisExtent; var controlPosition = controlModel.get('position', true); var showPlayBtn = showControl && controlModel.get('showPlayBtn', true); var showPrevBtn = showControl && controlModel.get('showPrevBtn', true); var showNextBtn = showControl && controlModel.get('showNextBtn', true); var xLeft = 0; var xRight = mainLength; // position[0] means left, position[1] means middle. if (controlPosition === 'left' || controlPosition === 'bottom') { showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap); showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap); showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap); } else { // 'top' 'right' showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap); showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap); showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap); } axisExtent = [xLeft, xRight]; if (timelineModel.get('inverse')) { axisExtent.reverse(); } return { viewRect: viewRect, mainLength: mainLength, orient: orient, rotation: rotationMap[orient], labelRotation: labelRotation, labelPosOpt: labelPosOpt, labelAlign: timelineModel.get('label.align') || labelAlignMap[orient], labelBaseline: timelineModel.get('label.verticalAlign') || timelineModel.get('label.baseline') || labelBaselineMap[orient], // Based on mainGroup. playPosition: playPosition, prevBtnPosition: prevBtnPosition, nextBtnPosition: nextBtnPosition, axisExtent: axisExtent, controlSize: controlSize, controlGap: controlGap }; }, _position: function (layoutInfo, timelineModel) { // Position is be called finally, because bounding rect is needed for // adapt content to fill viewRect (auto adapt offset). // Timeline may be not all in the viewRect when 'offset' is specified // as a number, because it is more appropriate that label aligns at // 'offset' but not the other edge defined by viewRect. var mainGroup = this._mainGroup; var labelGroup = this._labelGroup; var viewRect = layoutInfo.viewRect; if (layoutInfo.orient === 'vertical') { // transform to horizontal, inverse rotate by left-top point. var m = create$1(); var rotateOriginX = viewRect.x; var rotateOriginY = viewRect.y + viewRect.height; translate(m, m, [-rotateOriginX, -rotateOriginY]); rotate(m, m, -PI$4 / 2); translate(m, m, [rotateOriginX, rotateOriginY]); viewRect = viewRect.clone(); viewRect.applyTransform(m); } var viewBound = getBound(viewRect); var mainBound = getBound(mainGroup.getBoundingRect()); var labelBound = getBound(labelGroup.getBoundingRect()); var mainPosition = mainGroup.position; var labelsPosition = labelGroup.position; labelsPosition[0] = mainPosition[0] = viewBound[0][0]; var labelPosOpt = layoutInfo.labelPosOpt; if (isNaN(labelPosOpt)) { // '+' or '-' var mainBoundIdx = labelPosOpt === '+' ? 0 : 1; toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx); toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx); } else { var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1; toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx); labelsPosition[1] = mainPosition[1] + labelPosOpt; } mainGroup.attr('position', mainPosition); labelGroup.attr('position', labelsPosition); mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation; setOrigin(mainGroup); setOrigin(labelGroup); function setOrigin(targetGroup) { var pos = targetGroup.position; targetGroup.origin = [ viewBound[0][0] - pos[0], viewBound[1][0] - pos[1] ]; } function getBound(rect) { // [[xmin, xmax], [ymin, ymax]] return [ [rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height] ]; } function toBound(fromPos, from, to, dimIdx, boundIdx) { fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx]; } }, _createAxis: function (layoutInfo, timelineModel) { var data = timelineModel.getData(); var axisType = timelineModel.get('axisType'); var scale = createScaleByModel(timelineModel, axisType); var dataExtent = data.getDataExtent('value'); scale.setExtent(dataExtent[0], dataExtent[1]); this._customizeScale(scale, data); scale.niceTicks(); var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType); axis.model = timelineModel; return axis; }, _customizeScale: function (scale, data) { scale.getTicks = function () { return data.mapArray(['value'], function (value) { return value; }); }; scale.getTicksLabels = function () { return map(this.getTicks(), scale.getLabel, scale); }; }, _createGroup: function (name) { var newGroup = this['_' + name] = new Group(); this.group.add(newGroup); return newGroup; }, _renderAxisLine: function (layoutInfo, group, axis, timelineModel) { var axisExtent = axis.getExtent(); if (!timelineModel.get('lineStyle.show')) { return; } group.add(new Line({ shape: { x1: axisExtent[0], y1: 0, x2: axisExtent[1], y2: 0 }, style: extend( {lineCap: 'round'}, timelineModel.getModel('lineStyle').getLineStyle() ), silent: true, z2: 1 })); }, /** * @private */ _renderAxisTick: function (layoutInfo, group, axis, timelineModel) { var data = timelineModel.getData(); var ticks = axis.scale.getTicks(); each$28(ticks, function (value, dataIndex) { var tickCoord = axis.dataToCoord(value); var itemModel = data.getItemModel(dataIndex); var itemStyleModel = itemModel.getModel('itemStyle'); var hoverStyleModel = itemModel.getModel('emphasis.itemStyle'); var symbolOpt = { position: [tickCoord, 0], onclick: bind$6(this._changeTimeline, this, dataIndex) }; var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt); setHoverStyle(el, hoverStyleModel.getItemStyle()); if (itemModel.get('tooltip')) { el.dataIndex = dataIndex; el.dataModel = timelineModel; } else { el.dataIndex = el.dataModel = null; } }, this); }, /** * @private */ _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) { var labelModel = timelineModel.getModel('label'); if (!labelModel.get('show')) { return; } var data = timelineModel.getData(); var ticks = axis.scale.getTicks(); var labels = getFormattedLabels( axis, labelModel.get('formatter') ); var labelInterval = axis.getLabelInterval(); each$28(ticks, function (tick, dataIndex) { if (axis.isLabelIgnored(dataIndex, labelInterval)) { return; } var itemModel = data.getItemModel(dataIndex); var normalLabelModel = itemModel.getModel('label'); var hoverLabelModel = itemModel.getModel('emphasis.label'); var tickCoord = axis.dataToCoord(tick); var textEl = new Text({ position: [tickCoord, 0], rotation: layoutInfo.labelRotation - layoutInfo.rotation, onclick: bind$6(this._changeTimeline, this, dataIndex), silent: false }); setTextStyle(textEl.style, normalLabelModel, { text: labels[dataIndex], textAlign: layoutInfo.labelAlign, textVerticalAlign: layoutInfo.labelBaseline }); group.add(textEl); setHoverStyle( textEl, setTextStyle({}, hoverLabelModel) ); }, this); }, /** * @private */ _renderControl: function (layoutInfo, group, axis, timelineModel) { var controlSize = layoutInfo.controlSize; var rotation = layoutInfo.rotation; var itemStyle = timelineModel.getModel('controlStyle').getItemStyle(); var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle(); var rect = [0, -controlSize / 2, controlSize, controlSize]; var playState = timelineModel.getPlayState(); var inverse = timelineModel.get('inverse', true); makeBtn( layoutInfo.nextBtnPosition, 'controlStyle.nextIcon', bind$6(this._changeTimeline, this, inverse ? '-' : '+') ); makeBtn( layoutInfo.prevBtnPosition, 'controlStyle.prevIcon', bind$6(this._changeTimeline, this, inverse ? '+' : '-') ); makeBtn( layoutInfo.playPosition, 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'), bind$6(this._handlePlayClick, this, !playState), true ); function makeBtn(position, iconPath, onclick, willRotate) { if (!position) { return; } var opt = { position: position, origin: [controlSize / 2, 0], rotation: willRotate ? -rotation : 0, rectHover: true, style: itemStyle, onclick: onclick }; var btn = makeIcon(timelineModel, iconPath, rect, opt); group.add(btn); setHoverStyle(btn, hoverStyle); } }, _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) { var data = timelineModel.getData(); var currentIndex = timelineModel.getCurrentIndex(); var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle'); var me = this; var callback = { onCreate: function (pointer) { pointer.draggable = true; pointer.drift = bind$6(me._handlePointerDrag, me); pointer.ondragend = bind$6(me._handlePointerDragend, me); pointerMoveTo(pointer, currentIndex, axis, timelineModel, true); }, onUpdate: function (pointer) { pointerMoveTo(pointer, currentIndex, axis, timelineModel); } }; // Reuse when exists, for animation and drag. this._currentPointer = giveSymbol( pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback ); }, _handlePlayClick: function (nextState) { this._clearTimer(); this.api.dispatchAction({ type: 'timelinePlayChange', playState: nextState, from: this.uid }); }, _handlePointerDrag: function (dx, dy, e) { this._clearTimer(); this._pointerChangeTimeline([e.offsetX, e.offsetY]); }, _handlePointerDragend: function (e) { this._pointerChangeTimeline([e.offsetX, e.offsetY], true); }, _pointerChangeTimeline: function (mousePos, trigger) { var toCoord = this._toAxisCoord(mousePos)[0]; var axis = this._axis; var axisExtent = asc(axis.getExtent().slice()); toCoord > axisExtent[1] && (toCoord = axisExtent[1]); toCoord < axisExtent[0] && (toCoord = axisExtent[0]); this._currentPointer.position[0] = toCoord; this._currentPointer.dirty(); var targetDataIndex = this._findNearestTick(toCoord); var timelineModel = this.model; if (trigger || ( targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime') )) { this._changeTimeline(targetDataIndex); } }, _doPlayStop: function () { this._clearTimer(); if (this.model.getPlayState()) { this._timer = setTimeout( bind$6(handleFrame, this), this.model.get('playInterval') ); } function handleFrame() { // Do not cache var timelineModel = this.model; this._changeTimeline( timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1) ); } }, _toAxisCoord: function (vertex) { var trans = this._mainGroup.getLocalTransform(); return applyTransform$1(vertex, trans, true); }, _findNearestTick: function (axisCoord) { var data = this.model.getData(); var dist = Infinity; var targetDataIndex; var axis = this._axis; data.each(['value'], function (value, dataIndex) { var coord = axis.dataToCoord(value); var d = Math.abs(coord - axisCoord); if (d < dist) { dist = d; targetDataIndex = dataIndex; } }); return targetDataIndex; }, _clearTimer: function () { if (this._timer) { clearTimeout(this._timer); this._timer = null; } }, _changeTimeline: function (nextIndex) { var currentIndex = this.model.getCurrentIndex(); if (nextIndex === '+') { nextIndex = currentIndex + 1; } else if (nextIndex === '-') { nextIndex = currentIndex - 1; } this.api.dispatchAction({ type: 'timelineChange', currentIndex: nextIndex, from: this.uid }); } }); function getViewRect$4(model, api) { return getLayoutRect( model.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }, model.get('padding') ); } function makeIcon(timelineModel, objPath, rect, opts) { var icon = makePath( timelineModel.get(objPath).replace(/^path:\/\//, ''), clone(opts || {}), new BoundingRect(rect[0], rect[1], rect[2], rect[3]), 'center' ); return icon; } /** * Create symbol or update symbol * opt: basic position and event handlers */ function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) { var color = itemStyleModel.get('color'); if (!symbol) { var symbolType = hostModel.get('symbol'); symbol = createSymbol(symbolType, -1, -1, 2, 2, color); symbol.setStyle('strokeNoScale', true); group.add(symbol); callback && callback.onCreate(symbol); } else { symbol.setColor(color); group.add(symbol); // Group may be new, also need to add. callback && callback.onUpdate(symbol); } // Style var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']); symbol.setStyle(itemStyle); // Transform and events. opt = merge({ rectHover: true, z2: 100 }, opt, true); var symbolSize = hostModel.get('symbolSize'); symbolSize = symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize]; symbolSize[0] /= 2; symbolSize[1] /= 2; opt.scale = symbolSize; var symbolOffset = hostModel.get('symbolOffset'); if (symbolOffset) { var pos = opt.position = opt.position || [0, 0]; pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]); pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]); } var symbolRotate = hostModel.get('symbolRotate'); opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0; symbol.attr(opt); // FIXME // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed, // getBoundingRect will return wrong result. // (This is supposed to be resolved in zrender, but it is a little difficult to // leverage performance and auto updateTransform) // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol. symbol.updateTransform(); return symbol; } function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) { if (pointer.dragging) { return; } var pointerModel = timelineModel.getModel('checkpointStyle'); var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex)); if (noAnimation || !pointerModel.get('animation', true)) { pointer.attr({position: [toCoord, 0]}); } else { pointer.stopAnimation(true); pointer.animateTo( {position: [toCoord, 0]}, pointerModel.get('animationDuration', true), pointerModel.get('animationEasing', true) ); } } /** * DataZoom component entry */ registerPreprocessor(preprocessor$3); var ToolboxModel = extendComponentModel({ type: 'toolbox', layoutMode: { type: 'box', ignoreSize: true }, mergeDefaultAndTheme: function (option) { ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments); each$1(this.option.feature, function (featureOpt, featureName) { var Feature = get$1(featureName); Feature && merge(featureOpt, Feature.defaultOption); }); }, defaultOption: { show: true, z: 6, zlevel: 0, orient: 'horizontal', left: 'right', top: 'top', // right // bottom backgroundColor: 'transparent', borderColor: '#ccc', borderRadius: 0, borderWidth: 0, padding: 5, itemSize: 15, itemGap: 8, showTitle: true, iconStyle: { borderColor: '#666', color: 'none' }, emphasis: { iconStyle: { borderColor: '#3E98C5' } } // textStyle: {}, // feature } }); extendComponentView({ type: 'toolbox', render: function (toolboxModel, ecModel, api, payload) { var group = this.group; group.removeAll(); if (!toolboxModel.get('show')) { return; } var itemSize = +toolboxModel.get('itemSize'); var featureOpts = toolboxModel.get('feature') || {}; var features = this._features || (this._features = {}); var featureNames = []; each$1(featureOpts, function (opt, name) { featureNames.push(name); }); (new DataDiffer(this._featureNames || [], featureNames)) .add(processFeature) .update(processFeature) .remove(curry(processFeature, null)) .execute(); // Keep for diff. this._featureNames = featureNames; function processFeature(newIndex, oldIndex) { var featureName = featureNames[newIndex]; var oldName = featureNames[oldIndex]; var featureOpt = featureOpts[featureName]; var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel); var feature; if (featureName && !oldName) { // Create if (isUserFeatureName(featureName)) { feature = { model: featureModel, onclick: featureModel.option.onclick, featureName: featureName }; } else { var Feature = get$1(featureName); if (!Feature) { return; } feature = new Feature(featureModel, ecModel, api); } features[featureName] = feature; } else { feature = features[oldName]; // If feature does not exsit. if (!feature) { return; } feature.model = featureModel; feature.ecModel = ecModel; feature.api = api; } if (!featureName && oldName) { feature.dispose && feature.dispose(ecModel, api); return; } if (!featureModel.get('show') || feature.unusable) { feature.remove && feature.remove(ecModel, api); return; } createIconPaths(featureModel, feature, featureName); featureModel.setIconStatus = function (iconName, status) { var option = this.option; var iconPaths = this.iconPaths; option.iconStatus = option.iconStatus || {}; option.iconStatus[iconName] = status; // FIXME iconPaths[iconName] && iconPaths[iconName].trigger(status); }; if (feature.render) { feature.render(featureModel, ecModel, api, payload); } } function createIconPaths(featureModel, feature, featureName) { var iconStyleModel = featureModel.getModel('iconStyle'); var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle'); // If one feature has mutiple icon. they are orginaized as // { // icon: { // foo: '', // bar: '' // }, // title: { // foo: '', // bar: '' // } // } var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon'); var titles = featureModel.get('title') || {}; if (typeof icons === 'string') { var icon = icons; var title = titles; icons = {}; titles = {}; icons[featureName] = icon; titles[featureName] = title; } var iconPaths = featureModel.iconPaths = {}; each$1(icons, function (iconStr, iconName) { var path = createIcon( iconStr, {}, { x: -itemSize / 2, y: -itemSize / 2, width: itemSize, height: itemSize } ); path.setStyle(iconStyleModel.getItemStyle()); path.hoverStyle = iconStyleEmphasisModel.getItemStyle(); setHoverStyle(path); if (toolboxModel.get('showTitle')) { path.__title = titles[iconName]; path.on('mouseover', function () { // Should not reuse above hoverStyle, which might be modified. var hoverStyle = iconStyleEmphasisModel.getItemStyle(); path.setStyle({ text: titles[iconName], textPosition: hoverStyle.textPosition || 'bottom', textFill: hoverStyle.fill || hoverStyle.stroke || '#000', textAlign: hoverStyle.textAlign || 'center' }); }) .on('mouseout', function () { path.setStyle({ textFill: null }); }); } path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal'); group.add(path); path.on('click', bind( feature.onclick, feature, ecModel, api, iconName )); iconPaths[iconName] = path; }); } layout$3(group, toolboxModel, api); // Render background after group is layout // FIXME group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen group.eachChild(function (icon) { var titleText = icon.__title; var hoverStyle = icon.hoverStyle; // May be background element if (hoverStyle && titleText) { var rect = getBoundingRect( titleText, makeFont(hoverStyle) ); var offsetX = icon.position[0] + group.position[0]; var offsetY = icon.position[1] + group.position[1] + itemSize; var needPutOnTop = false; if (offsetY + rect.height > api.getHeight()) { hoverStyle.textPosition = 'top'; needPutOnTop = true; } var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8); if (offsetX + rect.width / 2 > api.getWidth()) { hoverStyle.textPosition = ['100%', topOffset]; hoverStyle.textAlign = 'right'; } else if (offsetX - rect.width / 2 < 0) { hoverStyle.textPosition = [0, topOffset]; hoverStyle.textAlign = 'left'; } } }); }, updateView: function (toolboxModel, ecModel, api, payload) { each$1(this._features, function (feature) { feature.updateView && feature.updateView(feature.model, ecModel, api, payload); }); }, // updateLayout: function (toolboxModel, ecModel, api, payload) { // zrUtil.each(this._features, function (feature) { // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload); // }); // }, remove: function (ecModel, api) { each$1(this._features, function (feature) { feature.remove && feature.remove(ecModel, api); }); this.group.removeAll(); }, dispose: function (ecModel, api) { each$1(this._features, function (feature) { feature.dispose && feature.dispose(ecModel, api); }); } }); function isUserFeatureName(featureName) { return featureName.indexOf('my') === 0; } var saveAsImageLang = lang.toolbox.saveAsImage; function SaveAsImage(model) { this.model = model; } SaveAsImage.defaultOption = { show: true, icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0', title: saveAsImageLang.title, type: 'png', // Default use option.backgroundColor // backgroundColor: '#fff', name: '', excludeComponents: ['toolbox'], pixelRatio: 1, lang: saveAsImageLang.lang.slice() }; SaveAsImage.prototype.unusable = !env$1.canvasSupported; var proto$4 = SaveAsImage.prototype; proto$4.onclick = function (ecModel, api) { var model = this.model; var title = model.get('name') || ecModel.get('title.0.text') || 'echarts'; var $a = document.createElement('a'); var type = model.get('type', true) || 'png'; $a.download = title + '.' + type; $a.target = '_blank'; var url = api.getConnectedDataURL({ type: type, backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff', excludeComponents: model.get('excludeComponents'), pixelRatio: model.get('pixelRatio') }); $a.href = url; // Chrome and Firefox if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) { var evt = new MouseEvent('click', { view: window, bubbles: true, cancelable: false }); $a.dispatchEvent(evt); } // IE else { if (window.navigator.msSaveOrOpenBlob) { var bstr = atob(url.split(',')[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while(n--) { u8arr[n] = bstr.charCodeAt(n); } var blob = new Blob([u8arr]); window.navigator.msSaveOrOpenBlob(blob, title + '.' + type); } else { var lang$$1 = model.get('lang'); var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' + '</body>'; var tab = window.open(); tab.document.write(html); } } }; register$1( 'saveAsImage', SaveAsImage ); var magicTypeLang = lang.toolbox.magicType; function MagicType(model) { this.model = model; } MagicType.defaultOption = { show: true, type: [], // Icon group icon: { line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4', bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7', stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z' }, // `line`, `bar`, `stack`, `tiled` title: clone(magicTypeLang.title), option: {}, seriesIndex: {} }; var proto$5 = MagicType.prototype; proto$5.getIcons = function () { var model = this.model; var availableIcons = model.get('icon'); var icons = {}; each$1(model.get('type'), function (type) { if (availableIcons[type]) { icons[type] = availableIcons[type]; } }); return icons; }; var seriesOptGenreator = { 'line': function (seriesType, seriesId, seriesModel, model) { if (seriesType === 'bar') { return merge({ id: seriesId, type: 'line', // Preserve data related option data: seriesModel.get('data'), stack: seriesModel.get('stack'), markPoint: seriesModel.get('markPoint'), markLine: seriesModel.get('markLine') }, model.get('option.line') || {}, true); } }, 'bar': function (seriesType, seriesId, seriesModel, model) { if (seriesType === 'line') { return merge({ id: seriesId, type: 'bar', // Preserve data related option data: seriesModel.get('data'), stack: seriesModel.get('stack'), markPoint: seriesModel.get('markPoint'), markLine: seriesModel.get('markLine') }, model.get('option.bar') || {}, true); } }, 'stack': function (seriesType, seriesId, seriesModel, model) { if (seriesType === 'line' || seriesType === 'bar') { return merge({ id: seriesId, stack: '__ec_magicType_stack__' }, model.get('option.stack') || {}, true); } }, 'tiled': function (seriesType, seriesId, seriesModel, model) { if (seriesType === 'line' || seriesType === 'bar') { return merge({ id: seriesId, stack: '' }, model.get('option.tiled') || {}, true); } } }; var radioTypes = [ ['line', 'bar'], ['stack', 'tiled'] ]; proto$5.onclick = function (ecModel, api, type) { var model = this.model; var seriesIndex = model.get('seriesIndex.' + type); // Not supported magicType if (!seriesOptGenreator[type]) { return; } var newOption = { series: [] }; var generateNewSeriesTypes = function (seriesModel) { var seriesType = seriesModel.subType; var seriesId = seriesModel.id; var newSeriesOpt = seriesOptGenreator[type]( seriesType, seriesId, seriesModel, model ); if (newSeriesOpt) { // PENDING If merge original option? defaults(newSeriesOpt, seriesModel.option); newOption.series.push(newSeriesOpt); } // Modify boundaryGap var coordSys = seriesModel.coordinateSystem; if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) { var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; if (categoryAxis) { var axisDim = categoryAxis.dim; var axisType = axisDim + 'Axis'; var axisModel = ecModel.queryComponents({ mainType: axisType, index: seriesModel.get(name + 'Index'), id: seriesModel.get(name + 'Id') })[0]; var axisIndex = axisModel.componentIndex; newOption[axisType] = newOption[axisType] || []; for (var i = 0; i <= axisIndex; i++) { newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {}; } newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false; } } }; each$1(radioTypes, function (radio) { if (indexOf(radio, type) >= 0) { each$1(radio, function (item) { model.setIconStatus(item, 'normal'); }); } }); model.setIconStatus(type, 'emphasis'); ecModel.eachComponent( { mainType: 'series', query: seriesIndex == null ? null : { seriesIndex: seriesIndex } }, generateNewSeriesTypes ); api.dispatchAction({ type: 'changeMagicType', currentType: type, newOption: newOption }); }; registerAction({ type: 'changeMagicType', event: 'magicTypeChanged', update: 'prepareAndUpdate' }, function (payload, ecModel) { ecModel.mergeOption(payload.newOption); }); register$1('magicType', MagicType); var dataViewLang = lang.toolbox.dataView; var BLOCK_SPLITER = new Array(60).join('-'); var ITEM_SPLITER = '\t'; /** * Group series into two types * 1. on category axis, like line, bar * 2. others, like scatter, pie * @param {module:echarts/model/Global} ecModel * @return {Object} * @inner */ function groupSeries(ecModel) { var seriesGroupByCategoryAxis = {}; var otherSeries = []; var meta = []; ecModel.eachRawSeries(function (seriesModel) { var coordSys = seriesModel.coordinateSystem; if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) { var baseAxis = coordSys.getBaseAxis(); if (baseAxis.type === 'category') { var key = baseAxis.dim + '_' + baseAxis.index; if (!seriesGroupByCategoryAxis[key]) { seriesGroupByCategoryAxis[key] = { categoryAxis: baseAxis, valueAxis: coordSys.getOtherAxis(baseAxis), series: [] }; meta.push({ axisDim: baseAxis.dim, axisIndex: baseAxis.index }); } seriesGroupByCategoryAxis[key].series.push(seriesModel); } else { otherSeries.push(seriesModel); } } else { otherSeries.push(seriesModel); } }); return { seriesGroupByCategoryAxis: seriesGroupByCategoryAxis, other: otherSeries, meta: meta }; } /** * Assemble content of series on cateogory axis * @param {Array.<module:echarts/model/Series>} series * @return {string} * @inner */ function assembleSeriesWithCategoryAxis(series) { var tables = []; each$1(series, function (group, key) { var categoryAxis = group.categoryAxis; var valueAxis = group.valueAxis; var valueAxisDim = valueAxis.dim; var headers = [' '].concat(map(group.series, function (series) { return series.name; })); var columns = [categoryAxis.model.getCategories()]; each$1(group.series, function (series) { columns.push(series.getRawData().mapArray(valueAxisDim, function (val) { return val; })); }); // Assemble table content var lines = [headers.join(ITEM_SPLITER)]; for (var i = 0; i < columns[0].length; i++) { var items = []; for (var j = 0; j < columns.length; j++) { items.push(columns[j][i]); } lines.push(items.join(ITEM_SPLITER)); } tables.push(lines.join('\n')); }); return tables.join('\n\n' + BLOCK_SPLITER + '\n\n'); } /** * Assemble content of other series * @param {Array.<module:echarts/model/Series>} series * @return {string} * @inner */ function assembleOtherSeries(series) { return map(series, function (series) { var data = series.getRawData(); var lines = [series.name]; var vals = []; data.each(data.dimensions, function () { var argLen = arguments.length; var dataIndex = arguments[argLen - 1]; var name = data.getName(dataIndex); for (var i = 0; i < argLen - 1; i++) { vals[i] = arguments[i]; } lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER)); }); return lines.join('\n'); }).join('\n\n' + BLOCK_SPLITER + '\n\n'); } /** * @param {module:echarts/model/Global} * @return {Object} * @inner */ function getContentFromModel(ecModel) { var result = groupSeries(ecModel); return { value: filter([ assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other) ], function (str) { return str.replace(/[\n\t\s]/g, ''); }).join('\n\n' + BLOCK_SPLITER + '\n\n'), meta: result.meta }; } function trim$1(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } /** * If a block is tsv format */ function isTSVFormat(block) { // Simple method to find out if a block is tsv format var firstLine = block.slice(0, block.indexOf('\n')); if (firstLine.indexOf(ITEM_SPLITER) >= 0) { return true; } } var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g'); /** * @param {string} tsv * @return {Object} */ function parseTSVContents(tsv) { var tsvLines = tsv.split(/\n+/g); var headers = trim$1(tsvLines.shift()).split(itemSplitRegex); var categories = []; var series = map(headers, function (header) { return { name: header, data: [] }; }); for (var i = 0; i < tsvLines.length; i++) { var items = trim$1(tsvLines[i]).split(itemSplitRegex); categories.push(items.shift()); for (var j = 0; j < items.length; j++) { series[j] && (series[j].data[i] = items[j]); } } return { series: series, categories: categories }; } /** * @param {string} str * @return {Array.<Object>} * @inner */ function parseListContents(str) { var lines = str.split(/\n+/g); var seriesName = trim$1(lines.shift()); var data = []; for (var i = 0; i < lines.length; i++) { var items = trim$1(lines[i]).split(itemSplitRegex); var name = ''; var value; var hasName = false; if (isNaN(items[0])) { // First item is name hasName = true; name = items[0]; items = items.slice(1); data[i] = { name: name, value: [] }; value = data[i].value; } else { value = data[i] = []; } for (var j = 0; j < items.length; j++) { value.push(+items[j]); } if (value.length === 1) { hasName ? (data[i].value = value[0]) : (data[i] = value[0]); } } return { name: seriesName, data: data }; } /** * @param {string} str * @param {Array.<Object>} blockMetaList * @return {Object} * @inner */ function parseContents(str, blockMetaList) { var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g')); var newOption = { series: [] }; each$1(blocks, function (block, idx) { if (isTSVFormat(block)) { var result = parseTSVContents(block); var blockMeta = blockMetaList[idx]; var axisKey = blockMeta.axisDim + 'Axis'; if (blockMeta) { newOption[axisKey] = newOption[axisKey] || []; newOption[axisKey][blockMeta.axisIndex] = { data: result.categories }; newOption.series = newOption.series.concat(result.series); } } else { var result = parseListContents(block); newOption.series.push(result); } }); return newOption; } /** * @alias {module:echarts/component/toolbox/feature/DataView} * @constructor * @param {module:echarts/model/Model} model */ function DataView(model) { this._dom = null; this.model = model; } DataView.defaultOption = { show: true, readOnly: false, optionToContent: null, contentToOption: null, icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28', title: clone(dataViewLang.title), lang: clone(dataViewLang.lang), backgroundColor: '#fff', textColor: '#000', textareaColor: '#fff', textareaBorderColor: '#333', buttonColor: '#c23531', buttonTextColor: '#fff' }; DataView.prototype.onclick = function (ecModel, api) { var container = api.getDom(); var model = this.model; if (this._dom) { container.removeChild(this._dom); } var root = document.createElement('div'); root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;'; root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements var header = document.createElement('h4'); var lang$$1 = model.get('lang') || []; header.innerHTML = lang$$1[0] || model.get('title'); header.style.cssText = 'margin: 10px 20px;'; header.style.color = model.get('textColor'); var viewMain = document.createElement('div'); var textarea = document.createElement('textarea'); viewMain.style.cssText = 'display:block;width:100%;overflow:auto;'; var optionToContent = model.get('optionToContent'); var contentToOption = model.get('contentToOption'); var result = getContentFromModel(ecModel); if (typeof optionToContent === 'function') { var htmlOrDom = optionToContent(api.getOption()); if (typeof htmlOrDom === 'string') { viewMain.innerHTML = htmlOrDom; } else if (isDom(htmlOrDom)) { viewMain.appendChild(htmlOrDom); } } else { // Use default textarea viewMain.appendChild(textarea); textarea.readOnly = model.get('readOnly'); textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;'; textarea.style.color = model.get('textColor'); textarea.style.borderColor = model.get('textareaBorderColor'); textarea.style.backgroundColor = model.get('textareaColor'); textarea.value = result.value; } var blockMetaList = result.meta; var buttonContainer = document.createElement('div'); buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;'; var buttonStyle = 'float:right;margin-right:20px;border:none;' + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px'; var closeButton = document.createElement('div'); var refreshButton = document.createElement('div'); buttonStyle += ';background-color:' + model.get('buttonColor'); buttonStyle += ';color:' + model.get('buttonTextColor'); var self = this; function close() { container.removeChild(root); self._dom = null; } addEventListener(closeButton, 'click', close); addEventListener(refreshButton, 'click', function () { var newOption; try { if (typeof contentToOption === 'function') { newOption = contentToOption(viewMain, api.getOption()); } else { newOption = parseContents(textarea.value, blockMetaList); } } catch (e) { close(); throw new Error('Data view format error ' + e); } if (newOption) { api.dispatchAction({ type: 'changeDataView', newOption: newOption }); } close(); }); closeButton.innerHTML = lang$$1[1]; refreshButton.innerHTML = lang$$1[2]; refreshButton.style.cssText = buttonStyle; closeButton.style.cssText = buttonStyle; !model.get('readOnly') && buttonContainer.appendChild(refreshButton); buttonContainer.appendChild(closeButton); // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea addEventListener(textarea, 'keydown', function (e) { if ((e.keyCode || e.which) === 9) { // get caret position/selection var val = this.value; var start = this.selectionStart; var end = this.selectionEnd; // set textarea value to: text before caret + tab + text after caret this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end); // put caret at right position again this.selectionStart = this.selectionEnd = start + 1; // prevent the focus lose stop(e); } }); root.appendChild(header); root.appendChild(viewMain); root.appendChild(buttonContainer); viewMain.style.height = (container.clientHeight - 80) + 'px'; container.appendChild(root); this._dom = root; }; DataView.prototype.remove = function (ecModel, api) { this._dom && api.getDom().removeChild(this._dom); }; DataView.prototype.dispose = function (ecModel, api) { this.remove(ecModel, api); }; /** * @inner */ function tryMergeDataOption(newData, originalData) { return map(newData, function (newVal, idx) { var original = originalData && originalData[idx]; if (isObject$1(original) && !isArray(original)) { if (isObject$1(newVal) && !isArray(newVal)) { newVal = newVal.value; } // Original data has option return defaults({ value: newVal }, original); } else { return newVal; } }); } register$1('dataView', DataView); registerAction({ type: 'changeDataView', event: 'dataViewChanged', update: 'prepareAndUpdate' }, function (payload, ecModel) { var newSeriesOptList = []; each$1(payload.newOption.series, function (seriesOpt) { var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0]; if (!seriesModel) { // New created series // Geuss the series type newSeriesOptList.push(extend({ // Default is scatter type: 'scatter' }, seriesOpt)); } else { var originalData = seriesModel.get('data'); newSeriesOptList.push({ name: seriesOpt.name, data: tryMergeDataOption(seriesOpt.data, originalData) }); } }); ecModel.mergeOption(defaults({ series: newSeriesOptList }, payload.newOption)); }); var each$30 = each$1; var ATTR$2 = '\0_ec_hist_store'; /** * @param {module:echarts/model/Global} ecModel * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]} */ function push(ecModel, newSnapshot) { var store = giveStore$1(ecModel); // If previous dataZoom can not be found, // complete an range with current range. each$30(newSnapshot, function (batchItem, dataZoomId) { var i = store.length - 1; for (; i >= 0; i--) { var snapshot = store[i]; if (snapshot[dataZoomId]) { break; } } if (i < 0) { // No origin range set, create one by current range. var dataZoomModel = ecModel.queryComponents( {mainType: 'dataZoom', subType: 'select', id: dataZoomId} )[0]; if (dataZoomModel) { var percentRange = dataZoomModel.getPercentRange(); store[0][dataZoomId] = { dataZoomId: dataZoomId, start: percentRange[0], end: percentRange[1] }; } } }); store.push(newSnapshot); } /** * @param {module:echarts/model/Global} ecModel * @return {Object} snapshot */ function pop(ecModel) { var store = giveStore$1(ecModel); var head = store[store.length - 1]; store.length > 1 && store.pop(); // Find top for all dataZoom. var snapshot = {}; each$30(head, function (batchItem, dataZoomId) { for (var i = store.length - 1; i >= 0; i--) { var batchItem = store[i][dataZoomId]; if (batchItem) { snapshot[dataZoomId] = batchItem; break; } } }); return snapshot; } /** * @param {module:echarts/model/Global} ecModel */ function clear$1(ecModel) { ecModel[ATTR$2] = null; } /** * @param {module:echarts/model/Global} ecModel * @return {number} records. always >= 1. */ function count(ecModel) { return giveStore$1(ecModel).length; } /** * [{key: dataZoomId, value: {dataZoomId, range}}, ...] * History length of each dataZoom may be different. * this._history[0] is used to store origin range. * @type {Array.<Object>} */ function giveStore$1(ecModel) { var store = ecModel[ATTR$2]; if (!store) { store = ecModel[ATTR$2] = [{}]; } return store; } DataZoomModel.extend({ type: 'dataZoom.select' }); DataZoomView.extend({ type: 'dataZoom.select' }); /** * DataZoom component entry */ // Use dataZoomSelect var dataZoomLang = lang.toolbox.dataZoom; var each$29 = each$1; // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_'; function DataZoom(model, ecModel, api) { /** * @private * @type {module:echarts/component/helper/BrushController} */ (this._brushController = new BrushController(api.getZr())) .on('brush', bind(this._onBrush, this)) .mount(); /** * @private * @type {boolean} */ this._isZoomActive; } DataZoom.defaultOption = { show: true, // Icon group icon: { zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1', back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26' }, // `zoom`, `back` title: clone(dataZoomLang.title) }; var proto$6 = DataZoom.prototype; proto$6.render = function (featureModel, ecModel, api, payload) { this.model = featureModel; this.ecModel = ecModel; this.api = api; updateZoomBtnStatus(featureModel, ecModel, this, payload, api); updateBackBtnStatus(featureModel, ecModel); }; proto$6.onclick = function (ecModel, api, type) { handlers$1[type].call(this); }; proto$6.remove = function (ecModel, api) { this._brushController.unmount(); }; proto$6.dispose = function (ecModel, api) { this._brushController.dispose(); }; /** * @private */ var handlers$1 = { zoom: function () { var nextActive = !this._isZoomActive; this.api.dispatchAction({ type: 'takeGlobalCursor', key: 'dataZoomSelect', dataZoomSelectActive: nextActive }); }, back: function () { this._dispatchZoomAction(pop(this.ecModel)); } }; /** * @private */ proto$6._onBrush = function (areas, opt) { if (!opt.isEnd || !areas.length) { return; } var snapshot = {}; var ecModel = this.ecModel; this._brushController.updateCovers([]); // remove cover var brushTargetManager = new BrushTargetManager( retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']} ); brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) { if (coordSys.type !== 'cartesian2d') { return; } var brushType = area.brushType; if (brushType === 'rect') { setBatch('x', coordSys, coordRange[0]); setBatch('y', coordSys, coordRange[1]); } else { setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange); } }); push(ecModel, snapshot); this._dispatchZoomAction(snapshot); function setBatch(dimName, coordSys, minMax) { var axis = coordSys.getAxis(dimName); var axisModel = axis.model; var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan(); if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) { minMax = sliderMove( 0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan ); } dataZoomModel && (snapshot[dataZoomModel.id] = { dataZoomId: dataZoomModel.id, startValue: minMax[0], endValue: minMax[1] }); } function findDataZoom(dimName, axisModel, ecModel) { var found; ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) { var has = dzModel.getAxisModel(dimName, axisModel.componentIndex); has && (found = dzModel); }); return found; } }; /** * @private */ proto$6._dispatchZoomAction = function (snapshot) { var batch = []; // Convert from hash map to array. each$29(snapshot, function (batchItem, dataZoomId) { batch.push(clone(batchItem)); }); batch.length && this.api.dispatchAction({ type: 'dataZoom', from: this.uid, batch: batch }); }; function retrieveAxisSetting(option) { var setting = {}; // Compatible with previous setting: null => all axis, false => no axis. each$1(['xAxisIndex', 'yAxisIndex'], function (name) { setting[name] = option[name]; setting[name] == null && (setting[name] = 'all'); (setting[name] === false || setting[name] === 'none') && (setting[name] = []); }); return setting; } function updateBackBtnStatus(featureModel, ecModel) { featureModel.setIconStatus( 'back', count(ecModel) > 1 ? 'emphasis' : 'normal' ); } function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) { var zoomActive = view._isZoomActive; if (payload && payload.type === 'takeGlobalCursor') { zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false; } view._isZoomActive = zoomActive; featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal'); var brushTargetManager = new BrushTargetManager( retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']} ); view._brushController .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) { return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared) ? 'lineX' : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared) ? 'lineY' : 'rect'; })) .enableBrush( zoomActive ? { brushType: 'auto', brushStyle: { // FIXME user customized? lineWidth: 0, fill: 'rgba(0,0,0,0.2)' } } : false ); } register$1('dataZoom', DataZoom); // Create special dataZoom option for select registerPreprocessor(function (option) { if (!option) { return; } var dataZoomOpts = option.dataZoom || (option.dataZoom = []); if (!isArray(dataZoomOpts)) { option.dataZoom = dataZoomOpts = [dataZoomOpts]; } var toolboxOpt = option.toolbox; if (toolboxOpt) { // Assume there is only one toolbox if (isArray(toolboxOpt)) { toolboxOpt = toolboxOpt[0]; } if (toolboxOpt && toolboxOpt.feature) { var dataZoomOpt = toolboxOpt.feature.dataZoom; addForAxis('xAxis', dataZoomOpt); addForAxis('yAxis', dataZoomOpt); } } function addForAxis(axisName, dataZoomOpt) { if (!dataZoomOpt) { return; } // Try not to modify model, because it is not merged yet. var axisIndicesName = axisName + 'Index'; var givenAxisIndices = dataZoomOpt[axisIndicesName]; if (givenAxisIndices != null && givenAxisIndices != 'all' && !isArray(givenAxisIndices) ) { givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices]; } forEachComponent(axisName, function (axisOpt, axisIndex) { if (givenAxisIndices != null && givenAxisIndices != 'all' && indexOf(givenAxisIndices, axisIndex) === -1 ) { return; } var newOpt = { type: 'select', $fromToolbox: true, // Id for merge mapping. id: DATA_ZOOM_ID_BASE + axisName + axisIndex }; // FIXME // Only support one axis now. newOpt[axisIndicesName] = axisIndex; dataZoomOpts.push(newOpt); }); } function forEachComponent(mainType, cb) { var opts = option[mainType]; if (!isArray(opts)) { opts = opts ? [opts] : []; } each$29(opts, cb); } }); var restoreLang = lang.toolbox.restore; function Restore(model) { this.model = model; } Restore.defaultOption = { show: true, icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5', title: restoreLang.title }; var proto$7 = Restore.prototype; proto$7.onclick = function (ecModel, api, type) { clear$1(ecModel); api.dispatchAction({ type: 'restore', from: this.uid }); }; register$1('restore', Restore); registerAction( {type: 'restore', event: 'restore', update: 'prepareAndUpdate'}, function (payload, ecModel) { ecModel.resetOption('recreate'); } ); var urn = 'urn:schemas-microsoft-com:vml'; var win = typeof window === 'undefined' ? null : window; var vmlInited = false; var doc = win && win.document; function createNode(tagName) { return doCreateNode(tagName); } // Avoid assign to an exported variable, for transforming to cjs. var doCreateNode; if (doc && !env$1.canvasSupported) { try { !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn); doCreateNode = function (tagName) { return doc.createElement('<zrvml:' + tagName + ' class="zrvml">'); }; } catch (e) { doCreateNode = function (tagName) { return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">'); }; } } // From raphael function initVML() { if (vmlInited || !doc) { return; } vmlInited = true; var styleSheets = doc.styleSheets; if (styleSheets.length < 31) { doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)'); } else { // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)'); } } // http://www.w3.org/TR/NOTE-VML // TODO Use proxy like svg instead of overwrite brush methods var CMD$3 = PathProxy.CMD; var round$3 = Math.round; var sqrt = Math.sqrt; var abs$1 = Math.abs; var cos = Math.cos; var sin = Math.sin; var mathMax$8 = Math.max; if (!env$1.canvasSupported) { var comma = ','; var imageTransformPrefix = 'progid:DXImageTransform.Microsoft'; var Z = 21600; var Z2 = Z / 2; var ZLEVEL_BASE = 100000; var Z_BASE$1 = 1000; var initRootElStyle = function (el) { el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;'; el.coordsize = Z + ',' + Z; el.coordorigin = '0,0'; }; var encodeHtmlAttribute = function (s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); }; var rgb2Str = function (r, g, b) { return 'rgb(' + [r, g, b].join(',') + ')'; }; var append = function (parent, child) { if (child && parent && child.parentNode !== parent) { parent.appendChild(child); } }; var remove = function (parent, child) { if (child && parent && child.parentNode === parent) { parent.removeChild(child); } }; var getZIndex = function (zlevel, z, z2) { // z 的取值范围为 [0, 1000] return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2; }; var parsePercent$3 = function (value, maxValue) { if (typeof value === 'string') { if (value.lastIndexOf('%') >= 0) { return parseFloat(value) / 100 * maxValue; } return parseFloat(value); } return value; }; /*************************************************** * PATH **************************************************/ var setColorAndOpacity = function (el, color, opacity) { var colorArr = parse(color); opacity = +opacity; if (isNaN(opacity)) { opacity = 1; } if (colorArr) { el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]); el.opacity = opacity * colorArr[3]; } }; var getColorAndAlpha = function (color) { var colorArr = parse(color); return [ rgb2Str(colorArr[0], colorArr[1], colorArr[2]), colorArr[3] ]; }; var updateFillNode = function (el, style, zrEl) { // TODO pattern var fill = style.fill; if (fill != null) { // Modified from excanvas if (fill instanceof Gradient) { var gradientType; var angle = 0; var focus = [0, 0]; // additional offset var shift = 0; // scale factor for offset var expansion = 1; var rect = zrEl.getBoundingRect(); var rectWidth = rect.width; var rectHeight = rect.height; if (fill.type === 'linear') { gradientType = 'gradient'; var transform = zrEl.transform; var p0 = [fill.x * rectWidth, fill.y * rectHeight]; var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight]; if (transform) { applyTransform(p0, p0, transform); applyTransform(p1, p1, transform); } var dx = p1[0] - p0[0]; var dy = p1[1] - p0[1]; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { gradientType = 'gradientradial'; var p0 = [fill.x * rectWidth, fill.y * rectHeight]; var transform = zrEl.transform; var scale$$1 = zrEl.scale; var width = rectWidth; var height = rectHeight; focus = [ // Percent in bounding rect (p0[0] - rect.x) / width, (p0[1] - rect.y) / height ]; if (transform) { applyTransform(p0, p0, transform); } width /= scale$$1[0] * Z; height /= scale$$1[1] * Z; var dimension = mathMax$8(width, height); shift = 2 * 0 / dimension; expansion = 2 * fill.r / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fill.colorStops.slice(); stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length$$1 = stops.length; // Color and alpha list of first and last stop var colorAndAlphaList = []; var colors = []; for (var i = 0; i < length$$1; i++) { var stop = stops[i]; var colorAndAlpha = getColorAndAlpha(stop.color); colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]); if (i === 0 || i === length$$1 - 1) { colorAndAlphaList.push(colorAndAlpha); } } if (length$$1 >= 2) { var color1 = colorAndAlphaList[0][0]; var color2 = colorAndAlphaList[1][0]; var opacity1 = colorAndAlphaList[0][1] * style.opacity; var opacity2 = colorAndAlphaList[1][1] * style.opacity; el.type = gradientType; el.method = 'none'; el.focus = '100%'; el.angle = angle; el.color = color1; el.color2 = color2; el.colors = colors.join(','); // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. el.opacity = opacity2; // FIXME g_o_:opacity ? el.opacity2 = opacity1; } if (gradientType === 'radial') { el.focusposition = focus.join(','); } } else { // FIXME Change from Gradient fill to color fill setColorAndOpacity(el, fill, style.opacity); } } }; var updateStrokeNode = function (el, style) { // if (style.lineJoin != null) { // el.joinstyle = style.lineJoin; // } // if (style.miterLimit != null) { // el.miterlimit = style.miterLimit * Z; // } // if (style.lineCap != null) { // el.endcap = style.lineCap; // } if (style.lineDash != null) { el.dashstyle = style.lineDash.join(' '); } if (style.stroke != null && !(style.stroke instanceof Gradient)) { setColorAndOpacity(el, style.stroke, style.opacity); } }; var updateFillAndStroke = function (vmlEl, type, style, zrEl) { var isFill = type == 'fill'; var el = vmlEl.getElementsByTagName(type)[0]; // Stroke must have lineWidth if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) { vmlEl[isFill ? 'filled' : 'stroked'] = 'true'; // FIXME Remove before updating, or set `colors` will throw error if (style[type] instanceof Gradient) { remove(vmlEl, el); } if (!el) { el = createNode(type); } isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style); append(vmlEl, el); } else { vmlEl[isFill ? 'filled' : 'stroked'] = 'false'; remove(vmlEl, el); } }; var points$3 = [[], [], []]; var pathDataToString = function (path, m) { var M = CMD$3.M; var C = CMD$3.C; var L = CMD$3.L; var A = CMD$3.A; var Q = CMD$3.Q; var str = []; var nPoint; var cmdStr; var cmd; var i; var xi; var yi; var data = path.data; var dataLength = path.len(); for (i = 0; i < dataLength;) { cmd = data[i++]; cmdStr = ''; nPoint = 0; switch (cmd) { case M: cmdStr = ' m '; nPoint = 1; xi = data[i++]; yi = data[i++]; points$3[0][0] = xi; points$3[0][1] = yi; break; case L: cmdStr = ' l '; nPoint = 1; xi = data[i++]; yi = data[i++]; points$3[0][0] = xi; points$3[0][1] = yi; break; case Q: case C: cmdStr = ' c '; nPoint = 3; var x1 = data[i++]; var y1 = data[i++]; var x2 = data[i++]; var y2 = data[i++]; var x3; var y3; if (cmd === Q) { // Convert quadratic to cubic using degree elevation x3 = x2; y3 = y2; x2 = (x2 + 2 * x1) / 3; y2 = (y2 + 2 * y1) / 3; x1 = (xi + 2 * x1) / 3; y1 = (yi + 2 * y1) / 3; } else { x3 = data[i++]; y3 = data[i++]; } points$3[0][0] = x1; points$3[0][1] = y1; points$3[1][0] = x2; points$3[1][1] = y2; points$3[2][0] = x3; points$3[2][1] = y3; xi = x3; yi = y3; break; case A: var x = 0; var y = 0; var sx = 1; var sy = 1; var angle = 0; if (m) { // Extract SRT from matrix x = m[4]; y = m[5]; sx = sqrt(m[0] * m[0] + m[1] * m[1]); sy = sqrt(m[2] * m[2] + m[3] * m[3]); angle = Math.atan2(-m[1] / sy, m[0] / sx); } var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var startAngle = data[i++] + angle; var endAngle = data[i++] + startAngle + angle; // FIXME // var psi = data[i++]; i++; var clockwise = data[i++]; var x0 = cx + cos(startAngle) * rx; var y0 = cy + sin(startAngle) * ry; var x1 = cx + cos(endAngle) * rx; var y1 = cy + sin(endAngle) * ry; var type = clockwise ? ' wa ' : ' at '; if (Math.abs(x0 - x1) < 1e-4) { // IE won't render arches drawn counter clockwise if x0 == x1. if (Math.abs(endAngle - startAngle) > 1e-2) { // Offset x0 by 1/80 of a pixel. Use something // that can be represented in binary if (clockwise) { x0 += 270 / Z; } } else { // Avoid case draw full circle if (Math.abs(y0 - cy) < 1e-4) { if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) { y1 -= 270 / Z; } else { y1 += 270 / Z; } } else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) { x1 += 270 / Z; } else { x1 -= 270 / Z; } } } str.push( type, round$3(((cx - rx) * sx + x) * Z - Z2), comma, round$3(((cy - ry) * sy + y) * Z - Z2), comma, round$3(((cx + rx) * sx + x) * Z - Z2), comma, round$3(((cy + ry) * sy + y) * Z - Z2), comma, round$3((x0 * sx + x) * Z - Z2), comma, round$3((y0 * sy + y) * Z - Z2), comma, round$3((x1 * sx + x) * Z - Z2), comma, round$3((y1 * sy + y) * Z - Z2) ); xi = x1; yi = y1; break; case CMD$3.R: var p0 = points$3[0]; var p1 = points$3[1]; // x0, y0 p0[0] = data[i++]; p0[1] = data[i++]; // x1, y1 p1[0] = p0[0] + data[i++]; p1[1] = p0[1] + data[i++]; if (m) { applyTransform(p0, p0, m); applyTransform(p1, p1, m); } p0[0] = round$3(p0[0] * Z - Z2); p1[0] = round$3(p1[0] * Z - Z2); p0[1] = round$3(p0[1] * Z - Z2); p1[1] = round$3(p1[1] * Z - Z2); str.push( // x0, y0 ' m ', p0[0], comma, p0[1], // x1, y0 ' l ', p1[0], comma, p0[1], // x1, y1 ' l ', p1[0], comma, p1[1], // x0, y1 ' l ', p0[0], comma, p1[1] ); break; case CMD$3.Z: // FIXME Update xi, yi str.push(' x '); } if (nPoint > 0) { str.push(cmdStr); for (var k = 0; k < nPoint; k++) { var p = points$3[k]; m && applyTransform(p, p, m); // 不 round 会非常慢 str.push( round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2), k < nPoint - 1 ? comma : '' ); } } } return str.join(''); }; // Rewrite the original path method Path.prototype.brushVML = function (vmlRoot) { var style = this.style; var vmlEl = this._vmlEl; if (!vmlEl) { vmlEl = createNode('shape'); initRootElStyle(vmlEl); this._vmlEl = vmlEl; } updateFillAndStroke(vmlEl, 'fill', style, this); updateFillAndStroke(vmlEl, 'stroke', style, this); var m = this.transform; var needTransform = m != null; var strokeEl = vmlEl.getElementsByTagName('stroke')[0]; if (strokeEl) { var lineWidth = style.lineWidth; // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. if (needTransform && !style.strokeNoScale) { var det = m[0] * m[3] - m[1] * m[2]; lineWidth *= sqrt(abs$1(det)); } strokeEl.weight = lineWidth + 'px'; } var path = this.path || (this.path = new PathProxy()); if (this.__dirtyPath) { path.beginPath(); this.buildPath(path, this.shape); path.toStatic(); this.__dirtyPath = false; } vmlEl.path = pathDataToString(path, this.transform); vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2); // Append to root append(vmlRoot, vmlEl); // Text if (style.text != null) { this.drawRectText(vmlRoot, this.getBoundingRect()); } else { this.removeRectText(vmlRoot); } }; Path.prototype.onRemove = function (vmlRoot) { remove(vmlRoot, this._vmlEl); this.removeRectText(vmlRoot); }; Path.prototype.onAdd = function (vmlRoot) { append(vmlRoot, this._vmlEl); this.appendRectText(vmlRoot); }; /*************************************************** * IMAGE **************************************************/ var isImage = function (img) { // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错 return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG'; // return img instanceof Image; }; // Rewrite the original path method ZImage.prototype.brushVML = function (vmlRoot) { var style = this.style; var image = style.image; // Image original width, height var ow; var oh; if (isImage(image)) { var src = image.src; if (src === this._imageSrc) { ow = this._imageWidth; oh = this._imageHeight; } else { var imageRuntimeStyle = image.runtimeStyle; var oldRuntimeWidth = imageRuntimeStyle.width; var oldRuntimeHeight = imageRuntimeStyle.height; imageRuntimeStyle.width = 'auto'; imageRuntimeStyle.height = 'auto'; // get the original size ow = image.width; oh = image.height; // and remove overides imageRuntimeStyle.width = oldRuntimeWidth; imageRuntimeStyle.height = oldRuntimeHeight; // Caching image original width, height and src this._imageSrc = src; this._imageWidth = ow; this._imageHeight = oh; } image = src; } else { if (image === this._imageSrc) { ow = this._imageWidth; oh = this._imageHeight; } } if (!image) { return; } var x = style.x || 0; var y = style.y || 0; var dw = style.width; var dh = style.height; var sw = style.sWidth; var sh = style.sHeight; var sx = style.sx || 0; var sy = style.sy || 0; var hasCrop = sw && sh; var vmlEl = this._vmlEl; if (!vmlEl) { // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。 // vmlEl = vmlCore.createNode('group'); vmlEl = doc.createElement('div'); initRootElStyle(vmlEl); this._vmlEl = vmlEl; } var vmlElStyle = vmlEl.style; var hasRotation = false; var m; var scaleX = 1; var scaleY = 1; if (this.transform) { m = this.transform; scaleX = sqrt(m[0] * m[0] + m[1] * m[1]); scaleY = sqrt(m[2] * m[2] + m[3] * m[3]); hasRotation = m[1] || m[2]; } if (hasRotation) { // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. // From excanvas var p0 = [x, y]; var p1 = [x + dw, y]; var p2 = [x, y + dh]; var p3 = [x + dw, y + dh]; applyTransform(p0, p0, m); applyTransform(p1, p1, m); applyTransform(p2, p2, m); applyTransform(p3, p3, m); var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]); var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]); var transformFilter = []; transformFilter.push('M11=', m[0] / scaleX, comma, 'M12=', m[2] / scaleY, comma, 'M21=', m[1] / scaleX, comma, 'M22=', m[3] / scaleY, comma, 'Dx=', round$3(x * scaleX + m[4]), comma, 'Dy=', round$3(y * scaleY + m[5])); vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0'; // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用 vmlElStyle.filter = imageTransformPrefix + '.Matrix(' + transformFilter.join('') + ', SizingMethod=clip)'; } else { if (m) { x = x * scaleX + m[4]; y = y * scaleY + m[5]; } vmlElStyle.filter = ''; vmlElStyle.left = round$3(x) + 'px'; vmlElStyle.top = round$3(y) + 'px'; } var imageEl = this._imageEl; var cropEl = this._cropEl; if (!imageEl) { imageEl = doc.createElement('div'); this._imageEl = imageEl; } var imageELStyle = imageEl.style; if (hasCrop) { // Needs know image original width and height if (! (ow && oh)) { var tmpImage = new Image(); var self = this; tmpImage.onload = function () { tmpImage.onload = null; ow = tmpImage.width; oh = tmpImage.height; // Adjust image width and height to fit the ratio destinationSize / sourceSize imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px'; imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px'; // Caching image original width, height and src self._imageWidth = ow; self._imageHeight = oh; self._imageSrc = image; }; tmpImage.src = image; } else { imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px'; imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px'; } if (! cropEl) { cropEl = doc.createElement('div'); cropEl.style.overflow = 'hidden'; this._cropEl = cropEl; } var cropElStyle = cropEl.style; cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX); cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY); cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx=' + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')'; if (! cropEl.parentNode) { vmlEl.appendChild(cropEl); } if (imageEl.parentNode != cropEl) { cropEl.appendChild(imageEl); } } else { imageELStyle.width = round$3(scaleX * dw) + 'px'; imageELStyle.height = round$3(scaleY * dh) + 'px'; vmlEl.appendChild(imageEl); if (cropEl && cropEl.parentNode) { vmlEl.removeChild(cropEl); this._cropEl = null; } } var filterStr = ''; var alpha = style.opacity; if (alpha < 1) { filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') '; } filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)'; imageELStyle.filter = filterStr; vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2); // Append to root append(vmlRoot, vmlEl); // Text if (style.text != null) { this.drawRectText(vmlRoot, this.getBoundingRect()); } }; ZImage.prototype.onRemove = function (vmlRoot) { remove(vmlRoot, this._vmlEl); this._vmlEl = null; this._cropEl = null; this._imageEl = null; this.removeRectText(vmlRoot); }; ZImage.prototype.onAdd = function (vmlRoot) { append(vmlRoot, this._vmlEl); this.appendRectText(vmlRoot); }; /*************************************************** * TEXT **************************************************/ var DEFAULT_STYLE_NORMAL = 'normal'; var fontStyleCache = {}; var fontStyleCacheCount = 0; var MAX_FONT_CACHE_SIZE = 100; var fontEl = document.createElement('div'); var getFontStyle = function (fontString) { var fontStyle = fontStyleCache[fontString]; if (!fontStyle) { // Clear cache if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) { fontStyleCacheCount = 0; fontStyleCache = {}; } var style = fontEl.style; var fontFamily; try { style.font = fontString; fontFamily = style.fontFamily.split(',')[0]; } catch (e) { } fontStyle = { style: style.fontStyle || DEFAULT_STYLE_NORMAL, variant: style.fontVariant || DEFAULT_STYLE_NORMAL, weight: style.fontWeight || DEFAULT_STYLE_NORMAL, size: parseFloat(style.fontSize || 12) | 0, family: fontFamily || 'Microsoft YaHei' }; fontStyleCache[fontString] = fontStyle; fontStyleCacheCount++; } return fontStyle; }; var textMeasureEl; // Overwrite measure text method $override$1('measureText', function (text, textFont) { var doc$$1 = doc; if (!textMeasureEl) { textMeasureEl = doc$$1.createElement('div'); textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;' + 'padding:0;margin:0;border:none;white-space:pre;'; doc.body.appendChild(textMeasureEl); } try { textMeasureEl.style.font = textFont; } catch (ex) { // Ignore failures to set to invalid font. } textMeasureEl.innerHTML = ''; // Don't use innerHTML or innerText because they allow markup/whitespace. textMeasureEl.appendChild(doc$$1.createTextNode(text)); return { width: textMeasureEl.offsetWidth }; }); var tmpRect$2 = new BoundingRect(); var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) { var style = this.style; // Optimize, avoid normalize every time. this.__dirty && normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!text) { return; } // Convert rich text to plain text. Rich text is not supported in // IE8-, but tags in rich text template will be removed. if (style.rich) { var contentBlock = parseRichText(text, style); text = []; for (var i = 0; i < contentBlock.lines.length; i++) { var tokens = contentBlock.lines[i].tokens; var textLine = []; for (var j = 0; j < tokens.length; j++) { textLine.push(tokens[j].text); } text.push(textLine.join('')); } text = text.join('\n'); } var x; var y; var align = style.textAlign; var verticalAlign = style.textVerticalAlign; var fontStyle = getFontStyle(style.font); // FIXME encodeHtmlAttribute ? var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' ' + fontStyle.size + 'px "' + fontStyle.family + '"'; textRect = textRect || getBoundingRect(text, font, align, verticalAlign); // Transform rect to view space var m = this.transform; // Ignore transform for text in other element if (m && !fromTextEl) { tmpRect$2.copy(rect); tmpRect$2.applyTransform(m); rect = tmpRect$2; } if (!fromTextEl) { var textPosition = style.textPosition; var distance$$1 = style.textDistance; // Text position represented by coord if (textPosition instanceof Array) { x = rect.x + parsePercent$3(textPosition[0], rect.width); y = rect.y + parsePercent$3(textPosition[1], rect.height); align = align || 'left'; } else { var res = adjustTextPositionOnRect( textPosition, rect, distance$$1 ); x = res.x; y = res.y; // Default align and baseline when has textPosition align = align || res.textAlign; verticalAlign = verticalAlign || res.textVerticalAlign; } } else { x = rect.x; y = rect.y; } x = adjustTextX(x, textRect.width, align); y = adjustTextY(y, textRect.height, verticalAlign); // Force baseline 'middle' y += textRect.height / 2; // var fontSize = fontStyle.size; // 1.75 is an arbitrary number, as there is no info about the text baseline // switch (baseline) { // case 'hanging': // case 'top': // y += fontSize / 1.75; // break; // case 'middle': // break; // default: // // case null: // // case 'alphabetic': // // case 'ideographic': // // case 'bottom': // y -= fontSize / 2.25; // break; // } // switch (align) { // case 'left': // break; // case 'center': // x -= textRect.width / 2; // break; // case 'right': // x -= textRect.width; // break; // case 'end': // align = elementStyle.direction == 'ltr' ? 'right' : 'left'; // break; // case 'start': // align = elementStyle.direction == 'rtl' ? 'right' : 'left'; // break; // default: // align = 'left'; // } var createNode$$1 = createNode; var textVmlEl = this._textVmlEl; var pathEl; var textPathEl; var skewEl; if (!textVmlEl) { textVmlEl = createNode$$1('line'); pathEl = createNode$$1('path'); textPathEl = createNode$$1('textpath'); skewEl = createNode$$1('skew'); // FIXME Why here is not cammel case // Align 'center' seems wrong textPathEl.style['v-text-align'] = 'left'; initRootElStyle(textVmlEl); pathEl.textpathok = true; textPathEl.on = true; textVmlEl.from = '0 0'; textVmlEl.to = '1000 0.05'; append(textVmlEl, skewEl); append(textVmlEl, pathEl); append(textVmlEl, textPathEl); this._textVmlEl = textVmlEl; } else { // 这里是在前面 appendChild 保证顺序的前提下 skewEl = textVmlEl.firstChild; pathEl = skewEl.nextSibling; textPathEl = pathEl.nextSibling; } var coords = [x, y]; var textVmlElStyle = textVmlEl.style; // Ignore transform for text in other element if (m && fromTextEl) { applyTransform(coords, coords, m); skewEl.on = true; skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0'; // Text position skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0); // Left top point as origin skewEl.origin = '0 0'; textVmlElStyle.left = '0px'; textVmlElStyle.top = '0px'; } else { skewEl.on = false; textVmlElStyle.left = round$3(x) + 'px'; textVmlElStyle.top = round$3(y) + 'px'; } textPathEl.string = encodeHtmlAttribute(text); // TODO try { textPathEl.style.font = font; } // Error font format catch (e) {} updateFillAndStroke(textVmlEl, 'fill', { fill: style.textFill, opacity: style.opacity }, this); updateFillAndStroke(textVmlEl, 'stroke', { stroke: style.textStroke, opacity: style.opacity, lineDash: style.lineDash }, this); textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2); // Attached to root append(vmlRoot, textVmlEl); }; var removeRectText = function (vmlRoot) { remove(vmlRoot, this._textVmlEl); this._textVmlEl = null; }; var appendRectText = function (vmlRoot) { append(vmlRoot, this._textVmlEl); }; var list = [RectText, Displayable, ZImage, Path, Text]; // In case Displayable has been mixed in RectText for (var i$3 = 0; i$3 < list.length; i$3++) { var proto$8 = list[i$3].prototype; proto$8.drawRectText = drawRectText; proto$8.removeRectText = removeRectText; proto$8.appendRectText = appendRectText; } Text.prototype.brushVML = function (vmlRoot) { var style = this.style; if (style.text != null) { this.drawRectText(vmlRoot, { x: style.x || 0, y: style.y || 0, width: 0, height: 0 }, this.getBoundingRect(), true); } else { this.removeRectText(vmlRoot); } }; Text.prototype.onRemove = function (vmlRoot) { this.removeRectText(vmlRoot); }; Text.prototype.onAdd = function (vmlRoot) { this.appendRectText(vmlRoot); }; } /** * VML Painter. * * @module zrender/vml/Painter */ function parseInt10$1(val) { return parseInt(val, 10); } /** * @alias module:zrender/vml/Painter */ function VMLPainter(root, storage) { initVML(); this.root = root; this.storage = storage; var vmlViewport = document.createElement('div'); var vmlRoot = document.createElement('div'); vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;'; vmlRoot.style.cssText = 'position:absolute;left:0;top:0;'; root.appendChild(vmlViewport); this._vmlRoot = vmlRoot; this._vmlViewport = vmlViewport; this.resize(); // Modify storage var oldDelFromStorage = storage.delFromStorage; var oldAddToStorage = storage.addToStorage; storage.delFromStorage = function (el) { oldDelFromStorage.call(storage, el); if (el) { el.onRemove && el.onRemove(vmlRoot); } }; storage.addToStorage = function (el) { // Displayable already has a vml node el.onAdd && el.onAdd(vmlRoot); oldAddToStorage.call(storage, el); }; this._firstPaint = true; } VMLPainter.prototype = { constructor: VMLPainter, getType: function () { return 'vml'; }, /** * @return {HTMLDivElement} */ getViewportRoot: function () { return this._vmlViewport; }, getViewportRootOffset: function () { var viewportRoot = this.getViewportRoot(); if (viewportRoot) { return { offsetLeft: viewportRoot.offsetLeft || 0, offsetTop: viewportRoot.offsetTop || 0 }; } }, /** * 刷新 */ refresh: function () { var list = this.storage.getDisplayList(true, true); this._paintList(list); }, _paintList: function (list) { var vmlRoot = this._vmlRoot; for (var i = 0; i < list.length; i++) { var el = list[i]; if (el.invisible || el.ignore) { if (!el.__alreadyNotVisible) { el.onRemove(vmlRoot); } // Set as already invisible el.__alreadyNotVisible = true; } else { if (el.__alreadyNotVisible) { el.onAdd(vmlRoot); } el.__alreadyNotVisible = false; if (el.__dirty) { el.beforeBrush && el.beforeBrush(); (el.brushVML || el.brush).call(el, vmlRoot); el.afterBrush && el.afterBrush(); } } el.__dirty = false; } if (this._firstPaint) { // Detached from document at first time // to avoid page refreshing too many times // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变 this._vmlViewport.appendChild(vmlRoot); this._firstPaint = false; } }, resize: function (width, height) { var width = width == null ? this._getWidth() : width; var height = height == null ? this._getHeight() : height; if (this._width != width || this._height != height) { this._width = width; this._height = height; var vmlViewportStyle = this._vmlViewport.style; vmlViewportStyle.width = width + 'px'; vmlViewportStyle.height = height + 'px'; } }, dispose: function () { this.root.innerHTML = ''; this._vmlRoot = this._vmlViewport = this.storage = null; }, getWidth: function () { return this._width; }, getHeight: function () { return this._height; }, clear: function () { if (this._vmlViewport) { this.root.removeChild(this._vmlViewport); } }, _getWidth: function () { var root = this.root; var stl = root.currentStyle; return ((root.clientWidth || parseInt10$1(stl.width)) - parseInt10$1(stl.paddingLeft) - parseInt10$1(stl.paddingRight)) | 0; }, _getHeight: function () { var root = this.root; var stl = root.currentStyle; return ((root.clientHeight || parseInt10$1(stl.height)) - parseInt10$1(stl.paddingTop) - parseInt10$1(stl.paddingBottom)) | 0; } }; // Not supported methods function createMethodNotSupport(method) { return function () { zrLog('In IE8.0 VML mode painter not support method "' + method + '"'); }; } // Unsupported methods each$1([ 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage' ], function (name) { VMLPainter.prototype[name] = createMethodNotSupport(name); }); registerPainter('vml', VMLPainter); var svgURI = 'http://www.w3.org/2000/svg'; function createElement(name) { return document.createElementNS(svgURI, name); } // TODO // 1. shadow // 2. Image: sx, sy, sw, sh var CMD$4 = PathProxy.CMD; var arrayJoin = Array.prototype.join; var NONE = 'none'; var mathRound = Math.round; var mathSin$3 = Math.sin; var mathCos$3 = Math.cos; var PI$5 = Math.PI; var PI2$7 = Math.PI * 2; var degree = 180 / PI$5; var EPSILON$4 = 1e-4; function round4(val) { return mathRound(val * 1e4) / 1e4; } function isAroundZero$1(val) { return val < EPSILON$4 && val > -EPSILON$4; } function pathHasFill(style, isText) { var fill = isText ? style.textFill : style.fill; return fill != null && fill !== NONE; } function pathHasStroke(style, isText) { var stroke = isText ? style.textStroke : style.stroke; return stroke != null && stroke !== NONE; } function setTransform(svgEl, m) { if (m) { attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')'); } } function attr(el, key, val) { if (!val || val.type !== 'linear' && val.type !== 'radial') { // Don't set attribute for gradient, since it need new dom nodes el.setAttribute(key, val); } } function attrXLink(el, key, val) { el.setAttributeNS('http://www.w3.org/1999/xlink', key, val); } function bindStyle(svgEl, style, isText) { if (pathHasFill(style, isText)) { var fill = isText ? style.textFill : style.fill; fill = fill === 'transparent' ? NONE : fill; /** * FIXME: * This is a temporary fix for Chrome's clipping bug * that happens when a clip-path is referring another one. * This fix should be used before Chrome's bug is fixed. * For an element that has clip-path, and fill is none, * set it to be "rgba(0, 0, 0, 0.002)" will hide the element. * Otherwise, it will show black fill color. * 0.002 is used because this won't work for alpha values smaller * than 0.002. * * See * https://bugs.chromium.org/p/chromium/issues/detail?id=659790 * for more information. */ if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) { fill = 'rgba(0, 0, 0, 0.002)'; } attr(svgEl, 'fill', fill); attr(svgEl, 'fill-opacity', style.opacity); } else { attr(svgEl, 'fill', NONE); } if (pathHasStroke(style, isText)) { var stroke = isText ? style.textStroke : style.stroke; stroke = stroke === 'transparent' ? NONE : stroke; attr(svgEl, 'stroke', stroke); var strokeWidth = isText ? style.textStrokeWidth : style.lineWidth; var strokeScale = !isText && style.strokeNoScale ? style.host.getLineScale() : 1; attr(svgEl, 'stroke-width', strokeWidth / strokeScale); // stroke then fill for text; fill then stroke for others attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill'); attr(svgEl, 'stroke-opacity', style.opacity); var lineDash = style.lineDash; if (lineDash) { attr(svgEl, 'stroke-dasharray', style.lineDash.join(',')); attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0)); } else { attr(svgEl, 'stroke-dasharray', ''); } // PENDING style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap); style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin); style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit); } else { attr(svgEl, 'stroke', NONE); } } /*************************************************** * PATH **************************************************/ function pathDataToString$1(path) { var str = []; var data = path.data; var dataLength = path.len(); for (var i = 0; i < dataLength;) { var cmd = data[i++]; var cmdStr = ''; var nData = 0; switch (cmd) { case CMD$4.M: cmdStr = 'M'; nData = 2; break; case CMD$4.L: cmdStr = 'L'; nData = 2; break; case CMD$4.Q: cmdStr = 'Q'; nData = 4; break; case CMD$4.C: cmdStr = 'C'; nData = 6; break; case CMD$4.A: var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var theta = data[i++]; var dTheta = data[i++]; var psi = data[i++]; var clockwise = data[i++]; var dThetaPositive = Math.abs(dTheta); var isCircle = isAroundZero$1(dThetaPositive - PI2$7) && !isAroundZero$1(dThetaPositive); var large = false; if (dThetaPositive >= PI2$7) { large = true; } else if (isAroundZero$1(dThetaPositive)) { large = false; } else { large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5) === !!clockwise; } var x0 = round4(cx + rx * mathCos$3(theta)); var y0 = round4(cy + ry * mathSin$3(theta)); // It will not draw if start point and end point are exactly the same // We need to shift the end point with a small value // FIXME A better way to draw circle ? if (isCircle) { if (clockwise) { dTheta = PI2$7 - 1e-4; } else { dTheta = -PI2$7 + 1e-4; } large = true; if (i === 9) { // Move to (x0, y0) only when CMD.A comes at the // first position of a shape. // For instance, when drawing a ring, CMD.A comes // after CMD.M, so it's unnecessary to move to // (x0, y0). str.push('M', x0, y0); } } var x = round4(cx + rx * mathCos$3(theta + dTheta)); var y = round4(cy + ry * mathSin$3(theta + dTheta)); // FIXME Ellipse str.push('A', round4(rx), round4(ry), mathRound(psi * degree), +large, +clockwise, x, y); break; case CMD$4.Z: cmdStr = 'Z'; break; case CMD$4.R: var x = round4(data[i++]); var y = round4(data[i++]); var w = round4(data[i++]); var h = round4(data[i++]); str.push( 'M', x, y, 'L', x + w, y, 'L', x + w, y + h, 'L', x, y + h, 'L', x, y ); break; } cmdStr && str.push(cmdStr); for (var j = 0; j < nData; j++) { // PENDING With scale str.push(round4(data[i++])); } } return str.join(' '); } var svgPath = {}; svgPath.brush = function (el) { var style = el.style; var svgEl = el.__svgEl; if (!svgEl) { svgEl = createElement('path'); el.__svgEl = svgEl; } if (!el.path) { el.createPathProxy(); } var path = el.path; if (el.__dirtyPath) { path.beginPath(); el.buildPath(path, el.shape); el.__dirtyPath = false; var pathStr = pathDataToString$1(path); if (pathStr.indexOf('NaN') < 0) { // Ignore illegal path, which may happen such in out-of-range // data in Calendar series. attr(svgEl, 'd', pathStr); } } bindStyle(svgEl, style); setTransform(svgEl, el.transform); if (style.text != null) { svgTextDrawRectText(el, el.getBoundingRect()); } }; /*************************************************** * IMAGE **************************************************/ var svgImage = {}; svgImage.brush = function (el) { var style = el.style; var image = style.image; if (image instanceof HTMLImageElement) { var src = image.src; image = src; } if (! image) { return; } var x = style.x || 0; var y = style.y || 0; var dw = style.width; var dh = style.height; var svgEl = el.__svgEl; if (! svgEl) { svgEl = createElement('image'); el.__svgEl = svgEl; } if (image !== el.__imageSrc) { attrXLink(svgEl, 'href', image); // Caching image src el.__imageSrc = image; } attr(svgEl, 'width', dw); attr(svgEl, 'height', dh); attr(svgEl, 'x', x); attr(svgEl, 'y', y); setTransform(svgEl, el.transform); if (style.text != null) { svgTextDrawRectText(el, el.getBoundingRect()); } }; /*************************************************** * TEXT **************************************************/ var svgText = {}; var tmpRect$3 = new BoundingRect(); var svgTextDrawRectText = function (el, rect, textRect) { var style = el.style; el.__dirty && normalizeTextStyle(style, true); var text = style.text; // Convert to string if (text == null) { // Draw no text only when text is set to null, but not '' return; } else { text += ''; } var textSvgEl = el.__textSvgEl; if (! textSvgEl) { textSvgEl = createElement('text'); el.__textSvgEl = textSvgEl; } var x; var y; var textPosition = style.textPosition; var distance = style.textDistance; var align = style.textAlign || 'left'; if (typeof style.fontSize === 'number') { style.fontSize += 'px'; } var font = style.font || [ style.fontStyle || '', style.fontWeight || '', style.fontSize || '', style.fontFamily || '' ].join(' ') || DEFAULT_FONT; var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign); textRect = getBoundingRect(text, font, align, verticalAlign); var lineHeight = textRect.lineHeight; // Text position represented by coord if (textPosition instanceof Array) { x = rect.x + textPosition[0]; y = rect.y + textPosition[1]; } else { var newPos = adjustTextPositionOnRect( textPosition, rect, distance ); x = newPos.x; y = newPos.y; verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign); align = newPos.textAlign; } attr(textSvgEl, 'alignment-baseline', verticalAlign); if (font) { textSvgEl.style.font = font; } var textPadding = style.textPadding; // Make baseline top attr(textSvgEl, 'x', x); attr(textSvgEl, 'y', y); bindStyle(textSvgEl, style, true); if (el instanceof Text || el.style.transformText) { // Transform text with element setTransform(textSvgEl, el.transform); } else { if (el.transform) { tmpRect$3.copy(rect); tmpRect$3.applyTransform(el.transform); rect = tmpRect$3; } else { var pos = el.transformCoordToGlobal(rect.x, rect.y); rect.x = pos[0]; rect.y = pos[1]; } // Text rotation, but no element transform var origin = style.textOrigin; if (origin === 'center') { x = textRect.width / 2 + x; y = textRect.height / 2 + y; } else if (origin) { x = origin[0] + x; y = origin[1] + y; } var rotate = -style.textRotation * 180 / Math.PI; attr(textSvgEl, 'transform', 'rotate(' + rotate + ',' + x + ',' + y + ')'); } var textLines = text.split('\n'); var nTextLines = textLines.length; var textAnchor = align; // PENDING if (textAnchor === 'left') { textAnchor = 'start'; textPadding && (x += textPadding[3]); } else if (textAnchor === 'right') { textAnchor = 'end'; textPadding && (x -= textPadding[1]); } else if (textAnchor === 'center') { textAnchor = 'middle'; textPadding && (x += (textPadding[3] - textPadding[1]) / 2); } var dy = 0; if (verticalAlign === 'baseline') { dy = -textRect.height + lineHeight; textPadding && (dy -= textPadding[2]); } else if (verticalAlign === 'middle') { dy = (-textRect.height + lineHeight) / 2; textPadding && (y += (textPadding[0] - textPadding[2]) / 2); } else { textPadding && (dy += textPadding[0]); } // Font may affect position of each tspan elements if (el.__text !== text || el.__textFont !== font) { var tspanList = el.__tspanList || []; el.__tspanList = tspanList; for (var i = 0; i < nTextLines; i++) { // Using cached tspan elements var tspan = tspanList[i]; if (! tspan) { tspan = tspanList[i] = createElement('tspan'); textSvgEl.appendChild(tspan); attr(tspan, 'alignment-baseline', verticalAlign); attr(tspan, 'text-anchor', textAnchor); } else { tspan.innerHTML = ''; } attr(tspan, 'x', x); attr(tspan, 'y', y + i * lineHeight + dy); tspan.appendChild(document.createTextNode(textLines[i])); } // Remove unsed tspan elements for (; i < tspanList.length; i++) { textSvgEl.removeChild(tspanList[i]); } tspanList.length = nTextLines; el.__text = text; el.__textFont = font; } else if (el.__tspanList.length) { // Update span x and y var len = el.__tspanList.length; for (var i = 0; i < len; ++i) { var tspan = el.__tspanList[i]; if (tspan) { attr(tspan, 'x', x); attr(tspan, 'y', y + i * lineHeight + dy); } } } }; function getVerticalAlignForSvg(verticalAlign) { if (verticalAlign === 'middle') { return 'middle'; } else if (verticalAlign === 'bottom') { return 'baseline'; } else { return 'hanging'; } } svgText.drawRectText = svgTextDrawRectText; svgText.brush = function (el) { var style = el.style; if (style.text != null) { // 强制设置 textPosition style.textPosition = [0, 0]; svgTextDrawRectText(el, { x: style.x || 0, y: style.y || 0, width: 0, height: 0 }, el.getBoundingRect()); } }; // Myers' Diff Algorithm // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js function Diff() {} Diff.prototype = { diff: function (oldArr, newArr, equals) { if (!equals) { equals = function (a, b) { return a === b; }; } this.equals = equals; var self = this; oldArr = oldArr.slice(); newArr = newArr.slice(); // Allow subclasses to massage the input prior to running var newLen = newArr.length; var oldLen = oldArr.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { var indices = []; for (var i = 0; i < newArr.length; i++) { indices.push(i); } // Identity per the equality and tokenizer return [{ indices: indices, count: newArr.length }]; } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath; var addPath = bestPath[diagonalPath - 1]; var removePath = bestPath[diagonalPath + 1]; var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) { return buildValues(self, basePath.components, newArr, oldArr); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } }, pushComponent: function (components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = {count: last.count + 1, added: added, removed: removed }; } else { components.push({count: 1, added: added, removed: removed }); } }, extractCommon: function (basePath, newArr, oldArr, diagonalPath) { var newLen = newArr.length; var oldLen = oldArr.length; var newPos = basePath.newPos; var oldPos = newPos - diagonalPath; var commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({count: commonCount}); } basePath.newPos = newPos; return oldPos; }, tokenize: function (value) { return value.slice(); }, join: function (value) { return value.slice(); } }; function buildValues(diff, components, newArr, oldArr) { var componentPos = 0; var componentLen = components.length; var newPos = 0; var oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { var indices = []; for (var i = newPos; i < newPos + component.count; i++) { indices.push(i); } component.indices = indices; newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { var indices = []; for (var i = oldPos; i < oldPos + component.count; i++) { indices.push(i); } component.indices = indices; oldPos += component.count; } } return components; } function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } var arrayDiff = new Diff(); var arrayDiff$1 = function (oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); }; /** * @file Manages elements that can be defined in <defs> in SVG, * e.g., gradients, clip path, etc. * @author Zhang Wenli */ var MARK_UNUSED = '0'; var MARK_USED = '1'; /** * Manages elements that can be defined in <defs> in SVG, * e.g., gradients, clip path, etc. * * @class * @param {number} zrId zrender instance id * @param {SVGElement} svgRoot root of SVG document * @param {string|string[]} tagNames possible tag names * @param {string} markLabel label name to make if the element * is used */ function Definable( zrId, svgRoot, tagNames, markLabel, domName ) { this._zrId = zrId; this._svgRoot = svgRoot; this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames; this._markLabel = markLabel; this._domName = domName || '_dom'; this.nextId = 0; } Definable.prototype.createElement = createElement; /** * Get the <defs> tag for svgRoot; optionally creates one if not exists. * * @param {boolean} isForceCreating if need to create when not exists * @return {SVGDefsElement} SVG <defs> element, null if it doesn't * exist and isForceCreating is false */ Definable.prototype.getDefs = function (isForceCreating) { var svgRoot = this._svgRoot; var defs = this._svgRoot.getElementsByTagName('defs'); if (defs.length === 0) { // Not exist if (isForceCreating) { defs = svgRoot.insertBefore( this.createElement('defs'), // Create new tag svgRoot.firstChild // Insert in the front of svg ); if (!defs.contains) { // IE doesn't support contains method defs.contains = function (el) { var children = defs.children; if (!children) { return false; } for (var i = children.length - 1; i >= 0; --i) { if (children[i] === el) { return true; } } return false; }; } return defs; } else { return null; } } else { return defs[0]; } }; /** * Update DOM element if necessary. * * @param {Object|string} element style element. e.g., for gradient, * it may be '#ccc' or {type: 'linear', ...} * @param {Function|undefined} onUpdate update callback */ Definable.prototype.update = function (element, onUpdate) { if (!element) { return; } var defs = this.getDefs(false); if (element[this._domName] && defs.contains(element[this._domName])) { // Update DOM if (typeof onUpdate === 'function') { onUpdate(element); } } else { // No previous dom, create new var dom = this.add(element); if (dom) { element[this._domName] = dom; } } }; /** * Add gradient dom to defs * * @param {SVGElement} dom DOM to be added to <defs> */ Definable.prototype.addDom = function (dom) { var defs = this.getDefs(true); defs.appendChild(dom); }; /** * Remove DOM of a given element. * * @param {SVGElement} element element to remove dom */ Definable.prototype.removeDom = function (element) { var defs = this.getDefs(false); if (defs && element[this._domName]) { defs.removeChild(element[this._domName]); element[this._domName] = null; } }; /** * Get DOMs of this element. * * @return {HTMLDomElement} doms of this defineable elements in <defs> */ Definable.prototype.getDoms = function () { var defs = this.getDefs(false); if (!defs) { // No dom when defs is not defined return []; } var doms = []; each$1(this._tagNames, function (tagName) { var tags = defs.getElementsByTagName(tagName); // Note that tags is HTMLCollection, which is array-like // rather than real array. // So `doms.concat(tags)` add tags as one object. doms = doms.concat([].slice.call(tags)); }); return doms; }; /** * Mark DOMs to be unused before painting, and clear unused ones at the end * of the painting. */ Definable.prototype.markAllUnused = function () { var doms = this.getDoms(); var that = this; each$1(doms, function (dom) { dom[that._markLabel] = MARK_UNUSED; }); }; /** * Mark a single DOM to be used. * * @param {SVGElement} dom DOM to mark */ Definable.prototype.markUsed = function (dom) { if (dom) { dom[this._markLabel] = MARK_USED; } }; /** * Remove unused DOMs defined in <defs> */ Definable.prototype.removeUnused = function () { var defs = this.getDefs(false); if (!defs) { // Nothing to remove return; } var doms = this.getDoms(); var that = this; each$1(doms, function (dom) { if (dom[that._markLabel] !== MARK_USED) { // Remove gradient defs.removeChild(dom); } }); }; /** * Get SVG proxy. * * @param {Displayable} displayable displayable element * @return {Path|Image|Text} svg proxy of given element */ Definable.prototype.getSvgProxy = function (displayable) { if (displayable instanceof Path) { return svgPath; } else if (displayable instanceof ZImage) { return svgImage; } else if (displayable instanceof Text) { return svgText; } else { return svgPath; } }; /** * Get text SVG element. * * @param {Displayable} displayable displayable element * @return {SVGElement} SVG element of text */ Definable.prototype.getTextSvgElement = function (displayable) { return displayable.__textSvgEl; }; /** * Get SVG element. * * @param {Displayable} displayable displayable element * @return {SVGElement} SVG element */ Definable.prototype.getSvgElement = function (displayable) { return displayable.__svgEl; }; /** * @file Manages SVG gradient elements. * @author Zhang Wenli */ /** * Manages SVG gradient elements. * * @class * @extends Definable * @param {number} zrId zrender instance id * @param {SVGElement} svgRoot root of SVG document */ function GradientManager(zrId, svgRoot) { Definable.call( this, zrId, svgRoot, ['linearGradient', 'radialGradient'], '__gradient_in_use__' ); } inherits(GradientManager, Definable); /** * Create new gradient DOM for fill or stroke if not exist, * but will not update gradient if exists. * * @param {SvgElement} svgElement SVG element to paint * @param {Displayable} displayable zrender displayable element */ GradientManager.prototype.addWithoutUpdate = function ( svgElement, displayable ) { if (displayable && displayable.style) { var that = this; each$1(['fill', 'stroke'], function (fillOrStroke) { if (displayable.style[fillOrStroke] && (displayable.style[fillOrStroke].type === 'linear' || displayable.style[fillOrStroke].type === 'radial') ) { var gradient = displayable.style[fillOrStroke]; var defs = that.getDefs(true); // Create dom in <defs> if not exists var dom; if (gradient._dom) { // Gradient exists dom = gradient._dom; if (!defs.contains(gradient._dom)) { // _dom is no longer in defs, recreate that.addDom(dom); } } else { // New dom dom = that.add(gradient); } that.markUsed(displayable); var id = dom.getAttribute('id'); svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')'); } }); } }; /** * Add a new gradient tag in <defs> * * @param {Gradient} gradient zr gradient instance * @return {SVGLinearGradientElement | SVGRadialGradientElement} * created DOM */ GradientManager.prototype.add = function (gradient) { var dom; if (gradient.type === 'linear') { dom = this.createElement('linearGradient'); } else if (gradient.type === 'radial') { dom = this.createElement('radialGradient'); } else { zrLog('Illegal gradient type.'); return null; } // Set dom id with gradient id, since each gradient instance // will have no more than one dom element. // id may exists before for those dirty elements, in which case // id should remain the same, and other attributes should be // updated. gradient.id = gradient.id || this.nextId++; dom.setAttribute('id', 'zr' + this._zrId + '-gradient-' + gradient.id); this.updateDom(gradient, dom); this.addDom(dom); return dom; }; /** * Update gradient. * * @param {Gradient} gradient zr gradient instance */ GradientManager.prototype.update = function (gradient) { var that = this; Definable.prototype.update.call(this, gradient, function () { var type = gradient.type; var tagName = gradient._dom.tagName; if (type === 'linear' && tagName === 'linearGradient' || type === 'radial' && tagName === 'radialGradient' ) { // Gradient type is not changed, update gradient that.updateDom(gradient, gradient._dom); } else { // Remove and re-create if type is changed that.removeDom(gradient); that.add(gradient); } }); }; /** * Update gradient dom * * @param {Gradient} gradient zr gradient instance * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom * DOM to update */ GradientManager.prototype.updateDom = function (gradient, dom) { if (gradient.type === 'linear') { dom.setAttribute('x1', gradient.x); dom.setAttribute('y1', gradient.y); dom.setAttribute('x2', gradient.x2); dom.setAttribute('y2', gradient.y2); } else if (gradient.type === 'radial') { dom.setAttribute('cx', gradient.x); dom.setAttribute('cy', gradient.y); dom.setAttribute('r', gradient.r); } else { zrLog('Illegal gradient type.'); return; } if (gradient.global) { // x1, x2, y1, y2 in range of 0 to canvas width or height dom.setAttribute('gradientUnits', 'userSpaceOnUse'); } else { // x1, x2, y1, y2 in range of 0 to 1 dom.setAttribute('gradientUnits', 'objectBoundingBox'); } // Remove color stops if exists dom.innerHTML = ''; // Add color stops var colors = gradient.colorStops; for (var i = 0, len = colors.length; i < len; ++i) { var stop = this.createElement('stop'); stop.setAttribute('offset', colors[i].offset * 100 + '%'); stop.setAttribute('stop-color', colors[i].color); dom.appendChild(stop); } // Store dom element in gradient, to avoid creating multiple // dom instances for the same gradient element gradient._dom = dom; }; /** * Mark a single gradient to be used * * @param {Displayable} displayable displayable element */ GradientManager.prototype.markUsed = function (displayable) { if (displayable.style) { var gradient = displayable.style.fill; if (gradient && gradient._dom) { Definable.prototype.markUsed.call(this, gradient._dom); } gradient = displayable.style.stroke; if (gradient && gradient._dom) { Definable.prototype.markUsed.call(this, gradient._dom); } } }; /** * @file Manages SVG clipPath elements. * @author Zhang Wenli */ /** * Manages SVG clipPath elements. * * @class * @extends Definable * @param {number} zrId zrender instance id * @param {SVGElement} svgRoot root of SVG document */ function ClippathManager(zrId, svgRoot) { Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__'); } inherits(ClippathManager, Definable); /** * Update clipPath. * * @param {Displayable} displayable displayable element */ ClippathManager.prototype.update = function (displayable) { var svgEl = this.getSvgElement(displayable); if (svgEl) { this.updateDom(svgEl, displayable.__clipPaths, false); } var textEl = this.getTextSvgElement(displayable); if (textEl) { // Make another clipPath for text, since it's transform // matrix is not the same with svgElement this.updateDom(textEl, displayable.__clipPaths, true); } this.markUsed(displayable); }; /** * Create an SVGElement of displayable and create a <clipPath> of its * clipPath * * @param {Displayable} parentEl parent element * @param {ClipPath[]} clipPaths clipPaths of parent element * @param {boolean} isText if parent element is Text */ ClippathManager.prototype.updateDom = function ( parentEl, clipPaths, isText ) { if (clipPaths && clipPaths.length > 0) { // Has clipPath, create <clipPath> with the first clipPath var defs = this.getDefs(true); var clipPath = clipPaths[0]; var clipPathEl; var id; var dom = isText ? '_textDom' : '_dom'; if (clipPath[dom]) { // Use a dom that is already in <defs> id = clipPath[dom].getAttribute('id'); clipPathEl = clipPath[dom]; // Use a dom that is already in <defs> if (!defs.contains(clipPathEl)) { // This happens when set old clipPath that has // been previously removed defs.appendChild(clipPathEl); } } else { // New <clipPath> id = 'zr' + this._zrId + '-clip-' + this.nextId; ++this.nextId; clipPathEl = this.createElement('clipPath'); clipPathEl.setAttribute('id', id); defs.appendChild(clipPathEl); clipPath[dom] = clipPathEl; } // Build path and add to <clipPath> var svgProxy = this.getSvgProxy(clipPath); if (clipPath.transform && clipPath.parent.invTransform && !isText ) { /** * If a clipPath has a parent with transform, the transform * of parent should not be considered when setting transform * of clipPath. So we need to transform back from parent's * transform, which is done by multiplying parent's inverse * transform. */ // Store old transform var transform = Array.prototype.slice.call( clipPath.transform ); // Transform back from parent, and brush path mul$1( clipPath.transform, clipPath.parent.invTransform, clipPath.transform ); svgProxy.brush(clipPath); // Set back transform of clipPath clipPath.transform = transform; } else { svgProxy.brush(clipPath); } var pathEl = this.getSvgElement(clipPath); clipPathEl.innerHTML = ''; /** * Use `cloneNode()` here to appendChild to multiple parents, * which may happend when Text and other shapes are using the same * clipPath. Since Text will create an extra clipPath DOM due to * different transform rules. */ clipPathEl.appendChild(pathEl.cloneNode()); parentEl.setAttribute('clip-path', 'url(#' + id + ')'); if (clipPaths.length > 1) { // Make the other clipPaths recursively this.updateDom(clipPathEl, clipPaths.slice(1), isText); } } else { // No clipPath if (parentEl) { parentEl.setAttribute('clip-path', 'none'); } } }; /** * Mark a single clipPath to be used * * @param {Displayable} displayable displayable element */ ClippathManager.prototype.markUsed = function (displayable) { var that = this; if (displayable.__clipPaths && displayable.__clipPaths.length > 0) { each$1(displayable.__clipPaths, function (clipPath) { if (clipPath._dom) { Definable.prototype.markUsed.call(that, clipPath._dom); } if (clipPath._textDom) { Definable.prototype.markUsed.call(that, clipPath._textDom); } }); } }; /** * @file Manages SVG shadow elements. * @author Zhang Wenli */ /** * Manages SVG shadow elements. * * @class * @extends Definable * @param {number} zrId zrender instance id * @param {SVGElement} svgRoot root of SVG document */ function ShadowManager(zrId, svgRoot) { Definable.call( this, zrId, svgRoot, ['filter'], '__filter_in_use__', '_shadowDom' ); } inherits(ShadowManager, Definable); /** * Create new shadow DOM for fill or stroke if not exist, * but will not update shadow if exists. * * @param {SvgElement} svgElement SVG element to paint * @param {Displayable} displayable zrender displayable element */ ShadowManager.prototype.addWithoutUpdate = function ( svgElement, displayable ) { if (displayable && hasShadow(displayable.style)) { var style = displayable.style; // Create dom in <defs> if not exists var dom; if (style._shadowDom) { // Gradient exists dom = style._shadowDom; var defs = this.getDefs(true); if (!defs.contains(style._shadowDom)) { // _shadowDom is no longer in defs, recreate this.addDom(dom); } } else { // New dom dom = this.add(displayable); } this.markUsed(displayable); var id = dom.getAttribute('id'); svgElement.style.filter = 'url(#' + id + ')'; } }; /** * Add a new shadow tag in <defs> * * @param {Displayable} displayable zrender displayable element * @return {SVGFilterElement} created DOM */ ShadowManager.prototype.add = function (displayable) { var dom = this.createElement('filter'); var style = displayable.style; // Set dom id with shadow id, since each shadow instance // will have no more than one dom element. // id may exists before for those dirty elements, in which case // id should remain the same, and other attributes should be // updated. style._shadowDomId = style._shadowDomId || this.nextId++; dom.setAttribute('id', 'zr' + this._zrId + '-shadow-' + style._shadowDomId); this.updateDom(displayable, dom); this.addDom(dom); return dom; }; /** * Update shadow. * * @param {Displayable} displayable zrender displayable element */ ShadowManager.prototype.update = function (svgElement, displayable) { var style = displayable.style; if (hasShadow(style)) { var that = this; Definable.prototype.update.call(this, displayable, function (style) { that.updateDom(displayable, style._shadowDom); }); } else { // Remove shadow this.remove(svgElement, style); } }; /** * Remove DOM and clear parent filter */ ShadowManager.prototype.remove = function (svgElement, style) { if (style._shadowDomId != null) { this.removeDom(style); svgElement.style.filter = ''; } }; /** * Update shadow dom * * @param {Displayable} displayable zrender displayable element * @param {SVGFilterElement} dom DOM to update */ ShadowManager.prototype.updateDom = function (displayable, dom) { var domChild = dom.getElementsByTagName('feDropShadow'); if (domChild.length === 0) { domChild = this.createElement('feDropShadow'); } else { domChild = domChild[0]; } var style = displayable.style; var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1; var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1; // TODO: textBoxShadowBlur is not supported yet var offsetX, offsetY, blur, color; if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) { offsetX = style.shadowOffsetX || 0; offsetY = style.shadowOffsetY || 0; blur = style.shadowBlur; color = style.shadowColor; } else if (style.textShadowBlur) { offsetX = style.textShadowOffsetX || 0; offsetY = style.textShadowOffsetY || 0; blur = style.textShadowBlur; color = style.textShadowColor; } else { // Remove shadow this.removeDom(dom, style); return; } domChild.setAttribute('dx', offsetX / scaleX); domChild.setAttribute('dy', offsetY / scaleY); domChild.setAttribute('flood-color', color); // Divide by two here so that it looks the same as in canvas // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur var stdDx = blur / 2 / scaleX; var stdDy = blur / 2 / scaleY; var stdDeviation = stdDx + ' ' + stdDy; domChild.setAttribute('stdDeviation', stdDeviation); // Fix filter clipping problem dom.setAttribute('x', '-100%'); dom.setAttribute('y', '-100%'); dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%'); dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%'); dom.appendChild(domChild); // Store dom element in shadow, to avoid creating multiple // dom instances for the same shadow element style._shadowDom = dom; }; /** * Mark a single shadow to be used * * @param {Displayable} displayable displayable element */ ShadowManager.prototype.markUsed = function (displayable) { var style = displayable.style; if (style && style._shadowDom) { Definable.prototype.markUsed.call(this, style._shadowDom); } }; function hasShadow(style) { // TODO: textBoxShadowBlur is not supported yet return style && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY || style.textShadowBlur || style.textShadowOffsetX || style.textShadowOffsetY); } /** * SVG Painter * @module zrender/svg/Painter */ function parseInt10$2(val) { return parseInt(val, 10); } function getSvgProxy(el) { if (el instanceof Path) { return svgPath; } else if (el instanceof ZImage) { return svgImage; } else if (el instanceof Text) { return svgText; } else { return svgPath; } } function checkParentAvailable(parent, child) { return child && parent && child.parentNode !== parent; } function insertAfter(parent, child, prevSibling) { if (checkParentAvailable(parent, child) && prevSibling) { var nextSibling = prevSibling.nextSibling; nextSibling ? parent.insertBefore(child, nextSibling) : parent.appendChild(child); } } function prepend(parent, child) { if (checkParentAvailable(parent, child)) { var firstChild = parent.firstChild; firstChild ? parent.insertBefore(child, firstChild) : parent.appendChild(child); } } function remove$1(parent, child) { if (child && parent && child.parentNode === parent) { parent.removeChild(child); } } function getTextSvgElement(displayable) { return displayable.__textSvgEl; } function getSvgElement(displayable) { return displayable.__svgEl; } /** * @alias module:zrender/svg/Painter * @constructor * @param {HTMLElement} root 绘图容器 * @param {module:zrender/Storage} storage * @param {Object} opts */ var SVGPainter = function (root, storage, opts, zrId) { this.root = root; this.storage = storage; this._opts = opts = extend({}, opts || {}); var svgRoot = createElement('svg'); svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); svgRoot.setAttribute('version', '1.1'); svgRoot.setAttribute('baseProfile', 'full'); svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;'; this.gradientManager = new GradientManager(zrId, svgRoot); this.clipPathManager = new ClippathManager(zrId, svgRoot); this.shadowManager = new ShadowManager(zrId, svgRoot); var viewport = document.createElement('div'); viewport.style.cssText = 'overflow:hidden;position:relative'; this._svgRoot = svgRoot; this._viewport = viewport; root.appendChild(viewport); viewport.appendChild(svgRoot); this.resize(opts.width, opts.height); this._visibleList = []; }; SVGPainter.prototype = { constructor: SVGPainter, getType: function () { return 'svg'; }, getViewportRoot: function () { return this._viewport; }, getViewportRootOffset: function () { var viewportRoot = this.getViewportRoot(); if (viewportRoot) { return { offsetLeft: viewportRoot.offsetLeft || 0, offsetTop: viewportRoot.offsetTop || 0 }; } }, refresh: function () { var list = this.storage.getDisplayList(true); this._paintList(list); }, setBackgroundColor: function (backgroundColor) { // TODO gradient this._viewport.style.background = backgroundColor; }, _paintList: function (list) { this.gradientManager.markAllUnused(); this.clipPathManager.markAllUnused(); this.shadowManager.markAllUnused(); var svgRoot = this._svgRoot; var visibleList = this._visibleList; var listLen = list.length; var newVisibleList = []; var i; for (i = 0; i < listLen; i++) { var displayable = list[i]; var svgProxy = getSvgProxy(displayable); var svgElement = getSvgElement(displayable) || getTextSvgElement(displayable); if (!displayable.invisible) { if (displayable.__dirty) { svgProxy && svgProxy.brush(displayable); // Update clipPath this.clipPathManager.update(displayable); // Update gradient and shadow if (displayable.style) { this.gradientManager .update(displayable.style.fill); this.gradientManager .update(displayable.style.stroke); this.shadowManager .update(svgElement, displayable); } displayable.__dirty = false; } newVisibleList.push(displayable); } } var diff = arrayDiff$1(visibleList, newVisibleList); var prevSvgElement; // First do remove, in case element moved to the head and do remove // after add for (i = 0; i < diff.length; i++) { var item = diff[i]; if (item.removed) { for (var k = 0; k < item.count; k++) { var displayable = visibleList[item.indices[k]]; var svgElement = getSvgElement(displayable); var textSvgElement = getTextSvgElement(displayable); remove$1(svgRoot, svgElement); remove$1(svgRoot, textSvgElement); } } } for (i = 0; i < diff.length; i++) { var item = diff[i]; if (item.added) { for (var k = 0; k < item.count; k++) { var displayable = newVisibleList[item.indices[k]]; var svgElement = getSvgElement(displayable); var textSvgElement = getTextSvgElement(displayable); prevSvgElement ? insertAfter(svgRoot, svgElement, prevSvgElement) : prepend(svgRoot, svgElement); if (svgElement) { insertAfter(svgRoot, textSvgElement, svgElement); } else if (prevSvgElement) { insertAfter( svgRoot, textSvgElement, prevSvgElement ); } else { prepend(svgRoot, textSvgElement); } // Insert text insertAfter(svgRoot, textSvgElement, svgElement); prevSvgElement = textSvgElement || svgElement || prevSvgElement; this.gradientManager .addWithoutUpdate(svgElement, displayable); this.shadowManager .addWithoutUpdate(prevSvgElement, displayable); this.clipPathManager.markUsed(displayable); } } else if (!item.removed) { for (var k = 0; k < item.count; k++) { var displayable = newVisibleList[item.indices[k]]; prevSvgElement = svgElement = getTextSvgElement(displayable) || getSvgElement(displayable) || prevSvgElement; this.gradientManager.markUsed(displayable); this.gradientManager .addWithoutUpdate(svgElement, displayable); this.shadowManager.markUsed(displayable); this.shadowManager .addWithoutUpdate(svgElement, displayable); this.clipPathManager.markUsed(displayable); } } } this.gradientManager.removeUnused(); this.clipPathManager.removeUnused(); this.shadowManager.removeUnused(); this._visibleList = newVisibleList; }, _getDefs: function (isForceCreating) { var svgRoot = this._svgRoot; var defs = this._svgRoot.getElementsByTagName('defs'); if (defs.length === 0) { // Not exist if (isForceCreating) { var defs = svgRoot.insertBefore( createElement('defs'), // Create new tag svgRoot.firstChild // Insert in the front of svg ); if (!defs.contains) { // IE doesn't support contains method defs.contains = function (el) { var children = defs.children; if (!children) { return false; } for (var i = children.length - 1; i >= 0; --i) { if (children[i] === el) { return true; } } return false; }; } return defs; } else { return null; } } else { return defs[0]; } }, resize: function (width, height) { var viewport = this._viewport; // FIXME Why ? viewport.style.display = 'none'; // Save input w/h var opts = this._opts; width != null && (opts.width = width); height != null && (opts.height = height); width = this._getSize(0); height = this._getSize(1); viewport.style.display = ''; if (this._width !== width || this._height !== height) { this._width = width; this._height = height; var viewportStyle = viewport.style; viewportStyle.width = width + 'px'; viewportStyle.height = height + 'px'; var svgRoot = this._svgRoot; // Set width by 'svgRoot.width = width' is invalid svgRoot.setAttribute('width', width); svgRoot.setAttribute('height', height); } }, /** * 获取绘图区域宽度 */ getWidth: function () { return this._width; }, /** * 获取绘图区域高度 */ getHeight: function () { return this._height; }, _getSize: function (whIdx) { var opts = this._opts; var wh = ['width', 'height'][whIdx]; var cwh = ['clientWidth', 'clientHeight'][whIdx]; var plt = ['paddingLeft', 'paddingTop'][whIdx]; var prb = ['paddingRight', 'paddingBottom'][whIdx]; if (opts[wh] != null && opts[wh] !== 'auto') { return parseFloat(opts[wh]); } var root = this.root; // IE8 does not support getComputedStyle, but it use VML. var stl = document.defaultView.getComputedStyle(root); return ( (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh])) - (parseInt10$2(stl[plt]) || 0) - (parseInt10$2(stl[prb]) || 0) ) | 0; }, dispose: function () { this.root.innerHTML = ''; this._svgRoot = this._viewport = this.storage = null; }, clear: function () { if (this._viewport) { this.root.removeChild(this._viewport); } }, pathToDataUrl: function () { this.refresh(); var html = this._svgRoot.outerHTML; return 'data:image/svg+xml;charset=UTF-8,' + html; } }; // Not supported methods function createMethodNotSupport$1(method) { return function () { zrLog('In SVG mode painter not support method "' + method + '"'); }; } // Unsuppoted methods each$1([ 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage' ], function (name) { SVGPainter.prototype[name] = createMethodNotSupport$1(name); }); registerPainter('svg', SVGPainter); // Import all charts and components 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; exports.zrender = zrender; exports.graphic = graphic; exports.number = number; exports.format = format; exports.throttle = throttle; exports.helper = helper; exports.matrix = matrix; exports.vector = vector; exports.color = color; exports.parseGeoJSON = parseGeoJson$1; exports.parseGeoJson = parseGeoJson; exports.util = ecUtil; exports.List = List; exports.Model = Model; exports.Axis = Axis; exports.env = env$1; }))); //# sourceMappingURL=echarts.js.map kodo - Gogs: Go Git Service

Nenhuma Descrição

watermark_utils.py 3.0KB

    # -*- coding: utf-8 -*- try: import Image import ImageEnhance except ImportError: from PIL import Image, ImageEnhance def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert 0 <= opacity <= 1 im = im.convert('RGBA') if im.mode != 'RGBA' else im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im def watermark(im, mark, position, opacity=1, maxsize=(0, 0), possize=(0, 0, None, None)): """ Add watermark to image """ if opacity < 1: mark = reduce_opacity(mark, opacity) # if im.mode != 'RGBA': # im = im.convert('RGBA') # Resize mark w, h = int(min(mark.size[0], maxsize[0]) if maxsize[0] else mark.size[0]), int(min(mark.size[1], maxsize[1]) if maxsize[1] else mark.size[1]) mark = mark.resize((w, h)) # Create a transparent layer the size of the image # Draw the watermark in that layer. layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # Scale, but preserve the aspect ratio ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w, h = int(mark.size[0] * ratio), int(mark.size[1] * ratio) w, h = int(min(w, maxsize[0]) if maxsize[0] else w), int(min(h, maxsize[1]) if maxsize[1] else h) mark = mark.resize((w, h)) possize += (None, ) * (4 - len(possize)) lx, ly, rx, ry = possize if rx is None or ry is None: layer.paste(mark, ((im.size[0] - (lx or w)) / 2, (im.size[1] - (ly or h)) / 2)) else: layer.paste(mark, ((im.size[0] - rx - w), ry)) else: layer.paste(mark, position) # Composite the watermark with the layer return Image.composite(layer, im, layer) def watermark_wrap(im_path, mark_path, save_path=''): im, mark = Image.open(im_path), Image.open(mark_path) # new_im = watermark(im, mark, (50, 50), 0.5) # new_im = watermark(im, mark, position='scale', opacity=1.0, maxsize=(400, 505.2), possize=(400, 400)) new_im = watermark(im, mark, position='scale', opacity=1.0, maxsize=(200, 247.1875), possize=(0, 0, 15, 15)) new_im.save(save_path or im_path) def watermark_test(): im, mark = Image.open('original_CGzC_10a50000c8811190.jpg'), Image.open('paiai_water_mark.png') watermark(im, mark, position='tile', opacity=0.5, maxsize=(40, 49.4375)).show() watermark(im, mark, position='scale', opacity=1.0, maxsize=(400, 494.375), possize=(400, 400)).show() watermark(im, mark, position='scale', opacity=1.0, maxsize=(200, 247.1875), possize=(0, 0, 10, 10)).show() watermark(im, mark, position=(50, 50), opacity=0.5, maxsize=(40, 49.4375)).show() if __name__ == '__main__': # watermark_test() watermark_wrap('original_CGzC_10a50000c8811190.jpg', 'paiai_water_mark.png')
Pai2/pai2 - Gogs: Go Git Service

2 Commity (ac69b15c9b7ad709e707d7d89d16ed5a79c96f72)

Autor SHA1 Wiadomość Data
  Brightcells fabef63211 set line_length=200 for isort 9 lat temu
  Brightcells 8b7c49ddb9 add app to add page user_agreement/contact_us 9 lat temu