PiecewiseModel.js 19.6 KB
Newer Older
P
pah100 已提交
1 2
define(function(require) {

P
pah100 已提交
3
    var VisualMapModel = require('./VisualMapModel');
P
pah100 已提交
4
    var zrUtil = require('zrender/core/util');
P
pah100 已提交
5
    var VisualMapping = require('../../visual/VisualMapping');
6
    var visualDefault = require('../../visual/visualDefault');
7
    var reformIntervals = require('../../util/number').reformIntervals;
P
pah100 已提交
8

P
pah100 已提交
9
    var PiecewiseModel = VisualMapModel.extend({
P
pah100 已提交
10

11
        type: 'visualMap.piecewise',
P
pah100 已提交
12

P
pah100 已提交
13 14 15
        /**
         * Order Rule:
         *
P
pah100 已提交
16
         * option.categories / option.pieces / option.text / option.selected:
P
pah100 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
         *     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.
         */

P
pah100 已提交
33 34 35 36
        /**
         * @protected
         */
        defaultOption: {
P
pah100 已提交
37 38 39
            selected: null,             // Object. If not specified, means selected.
                                        // When pieces and splitNumber: {'0': true, '5': true}
                                        // When categories: {'cate1': false, 'cate3': true}
P
pah100 已提交
40
                                        // When selected === false, means all unselected.
41 42 43 44

            minOpen: false,             // Whether include values that smaller than `min`.
            maxOpen: false,             // Whether include values that bigger than `max`.

P
pah100 已提交
45
            align: 'auto',              // 'auto', 'left', 'right'
P
pah100 已提交
46 47 48 49
            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.
P
pah100 已提交
50
            itemSymbol: 'roundRect',
P
pah100 已提交
51
            pieceList: null,            // Each item is Object, with some of those attrs:
52 53
                                        // {min, max, lt, gt, lte, gte, value,
                                        // color, colorSaturation, colorAlpha, opacity,
P
pah100 已提交
54 55 56 57 58 59 60 61 62 63
                                        // 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.
64 65 66 67
            hoverLink: true,            // Enable hover highlight.

            showLabel: null             // By default, when text is used, label will hide (the logic
                                        // is remained for compatibility reason)
P
pah100 已提交
68 69 70 71 72
        },

        /**
         * @override
         */
P
pah100 已提交
73 74
        optionUpdated: function (newOption, isInit) {
            PiecewiseModel.superApply(this, 'optionUpdated', arguments);
P
pah100 已提交
75 76

            /**
P
pah100 已提交
77
             * The order is always [low, ..., high].
P
pah100 已提交
78 79 80 81 82 83 84 85
             * [{text: string, interval: Array.<number>}, ...]
             * @private
             * @type {Array.<Object>}
             */
            this._pieceList = [];

            this.resetExtent();

P
pah100 已提交
86 87 88 89
            /**
             * 'pieces', 'categories', 'splitNumber'
             * @type {string}
             */
P
pah100 已提交
90
            var mode = this._mode = this._determineMode();
P
pah100 已提交
91

P
pah100 已提交
92
            resetMethods[this._mode].call(this);
P
pah100 已提交
93

P
pah100 已提交
94
            this._resetSelected(newOption, isInit);
P
pah100 已提交
95

P
pah100 已提交
96
            var categories = this.option.categories;
P
pah100 已提交
97

P
pah100 已提交
98
            this.resetVisual(function (mappingOption, state) {
P
pah100 已提交
99 100 101 102 103
                if (mode === 'categories') {
                    mappingOption.mappingMethod = 'category';
                    mappingOption.categories = zrUtil.clone(categories);
                }
                else {
P
pah100 已提交
104
                    mappingOption.dataExtent = this.getExtent();
P
pah100 已提交
105 106 107 108
                    mappingOption.mappingMethod = 'piecewise';
                    mappingOption.pieceList = zrUtil.map(this._pieceList, function (piece) {
                        var piece = zrUtil.clone(piece);
                        if (state !== 'inRange') {
109 110
                            // FIXME
                            // outOfRange do not support special visual in pieces.
P
pah100 已提交
111 112 113 114 115
                            piece.visual = null;
                        }
                        return piece;
                    });
                }
P
pah100 已提交
116
            });
P
pah100 已提交
117 118
        },

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        /**
         * @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();

            zrUtil.each(option.pieces, function (piece) {
                zrUtil.each(visualTypes, function (visualType) {
                    if (piece.hasOwnProperty(visualType)) {
                        visualTypesInPieces[visualType] = 1;
                    }
                });
            });

            zrUtil.each(visualTypesInPieces, function (v, visualType) {
                var exists = 0;
                zrUtil.each(this.stateList, function (state) {
                    exists |= has(option, state, visualType)
                        || has(option.target, state, visualType);
                }, this);

                !exists && zrUtil.each(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] && (
                    zrUtil.isObject(obj[state])
                        ? obj[state].hasOwnProperty(visualType)
                        : obj[state] === visualType // e.g., inRange: 'symbol'
                );
            }

            VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
        },

P
pah100 已提交
170
        _resetSelected: function (newOption, isInit) {
P
pah100 已提交
171 172 173
            var thisOption = this.option;
            var pieceList = this._pieceList;

P
pah100 已提交
174 175 176 177 178 179 180
            // Selected do not merge but all override.
            var selected = (isInit ? thisOption : newOption).selected || {};
            thisOption.selected = selected;

            // Consider 'not specified' means true.
            zrUtil.each(pieceList, function (piece, index) {
                var key = this.getSelectedMapKey(piece);
1
100pah 已提交
181
                if (!selected.hasOwnProperty(key)) {
P
pah100 已提交
182
                    selected[key] = true;
P
pah100 已提交
183
                }
P
pah100 已提交
184
            }, this);
P
pah100 已提交
185

P
pah100 已提交
186
            if (thisOption.selectedMode === 'single') {
P
pah100 已提交
187 188
                // Ensure there is only one selected.
                var hasSel = false;
P
pah100 已提交
189

P
pah100 已提交
190
                zrUtil.each(pieceList, function (piece, index) {
P
pah100 已提交
191 192
                    var key = this.getSelectedMapKey(piece);
                    if (selected[key]) {
P
pah100 已提交
193
                        hasSel
P
pah100 已提交
194
                            ? (selected[key] = false)
P
pah100 已提交
195 196
                            : (hasSel = true);
                    }
P
pah100 已提交
197
                }, this);
P
pah100 已提交
198
            }
P
pah100 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
            // 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}
         */
P
pah100 已提交
221
        _determineMode: function () {
P
pah100 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
            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 = zrUtil.clone(selected);
P
pah100 已提交
237 238
        },

P
pah100 已提交
239 240 241 242 243
        /**
         * @public
         * @override
         */
        getValueState: function (value) {
P
pah100 已提交
244
            var index = VisualMapping.findPieceIndex(value, this._pieceList);
P
pah100 已提交
245 246

            return index != null
P
pah100 已提交
247
                ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
P
pah100 已提交
248 249 250
                    ? 'inRange' : 'outOfRange'
                )
                : 'outOfRange';
P
pah100 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        },

        /**
         * @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);
                }, true, this);

P
pah100 已提交
271
                result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
P
pah100 已提交
272 273
            }, this);

P
pah100 已提交
274 275 276
            return result;
        },

277 278
        /**
         * @private
279 280
         * @param {Object} piece piece.value or piece.interval is required.
         * @return {number} Can be Infinity or -Infinity
281 282 283 284 285 286 287 288 289 290 291 292
         */
        getRepresentValue: function (piece) {
            var representValue;
            if (this.isCategory()) {
                representValue = piece.value;
            }
            else {
                if (piece.value != null) {
                    representValue = piece.value;
                }
                else {
                    var pieceInterval = piece.interval || [];
293 294 295
                    representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
                        ? 0
                        : (pieceInterval[0] + pieceInterval[1]) / 2;
296 297 298 299 300
                }
            }
            return representValue;
        },

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        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]});
            }
342

343
            var curr = -Infinity;
344
            zrUtil.each(pieceList, function (piece) {
345 346
                var interval = piece.interval;
                if (interval) {
347 348 349
                    // Fulfill gap.
                    interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
                    setStop(interval.slice());
350 351 352 353
                    curr = interval[1];
                }
            }, this);

354
            return {stops: stops, outerColors: outerColors};
P
pah100 已提交
355 356 357 358 359 360 361 362 363 364 365 366
        }

    });

    /**
     * Key is this._mode
     * @type {Object}
     * @this {module:echarts/component/viusalMap/PiecewiseMode}
     */
    var resetMethods = {

        splitNumber: function () {
P
pah100 已提交
367
            var thisOption = this.option;
368
            var pieceList = this._pieceList;
369
            var precision = Math.min(thisOption.precision, 20);
P
pah100 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382
            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);

383
            var index = 0;
P
pah100 已提交
384

385
            if (thisOption.minOpen) {
386
                pieceList.push({
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
                    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++,
402 403
                    interval: [curr, max],
                    close: [1, 1]
P
pah100 已提交
404 405
                });
            }
406

407 408 409 410 411 412 413 414
            if (thisOption.maxOpen) {
                pieceList.push({
                    index: index++,
                    interval: [dataExtent[1], Infinity],
                    close: [0, 0]
                });
            }

415
            reformIntervals(pieceList);
416 417 418 419

            zrUtil.each(pieceList, function (piece) {
                piece.text = this.formatValueText(piece.interval);
            }, this);
P
pah100 已提交
420 421
        },

P
pah100 已提交
422
        categories: function () {
P
pah100 已提交
423 424 425 426
            var thisOption = this.option;
            zrUtil.each(thisOption.categories, function (cate) {
                // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
                // 是否改一致。
P
pah100 已提交
427
                this._pieceList.push({
P
pah100 已提交
428
                    text: this.formatValueText(cate, true),
P
pah100 已提交
429 430 431
                    value: cate
                });
            }, this);
P
pah100 已提交
432 433

            // See "Order Rule".
P
pah100 已提交
434
            normalizeReverse(thisOption, this._pieceList);
P
pah100 已提交
435 436
        },

P
pah100 已提交
437
        pieces: function () {
P
pah100 已提交
438
            var thisOption = this.option;
439 440
            var pieceList = this._pieceList;

P
pah100 已提交
441
            zrUtil.each(thisOption.pieces, function (pieceListItem, index) {
P
pah100 已提交
442

P
pah100 已提交
443 444
                if (!zrUtil.isObject(pieceListItem)) {
                    pieceListItem = {value: pieceListItem};
P
pah100 已提交
445 446
                }

P
pah100 已提交
447
                var item = {text: '', index: index};
P
pah100 已提交
448

P
pah100 已提交
449 450
                if (pieceListItem.label != null) {
                    item.text = pieceListItem.label;
P
pah100 已提交
451
                }
P
pah100 已提交
452

P
pah100 已提交
453
                if (pieceListItem.hasOwnProperty('value')) {
454 455 456
                    var value = item.value = pieceListItem.value;
                    item.interval = [value, value];
                    item.close = [1, 1];
P
pah100 已提交
457 458
                }
                else {
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
                    // `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.'
                            );
                        }
P
pah100 已提交
487
                    }
P
pah100 已提交
488

489 490 491 492
                    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];
P
pah100 已提交
493
                    }
P
pah100 已提交
494 495
                }

P
pah100 已提交
496
                item.visual = VisualMapping.retrieveVisuals(pieceListItem);
P
pah100 已提交
497

498
                pieceList.push(item);
P
pah100 已提交
499

P
pah100 已提交
500 501 502
            }, this);

            // See "Order Rule".
503 504
            normalizeReverse(thisOption, pieceList);
            // Only pieces
505
            reformIntervals(pieceList);
506 507 508 509 510 511 512 513 514 515

            zrUtil.each(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);
P
pah100 已提交
516
        }
P
pah100 已提交
517
    };
P
pah100 已提交
518

519
    function normalizeReverse(thisOption, pieceList) {
P
pah100 已提交
520 521
        var inverse = thisOption.inverse;
        if (thisOption.orient === 'vertical' ? !inverse : inverse) {
522 523 524 525
             pieceList.reverse();
        }
    }

P
pah100 已提交
526
    return PiecewiseModel;
P
pah100 已提交
527
});