TreemapView.js 20.8 KB
Newer Older
P
pah100 已提交
1
 define(function(require) {
P
pah100 已提交
2 3 4 5

    var zrUtil = require('zrender/core/util');
    var graphic = require('../../util/graphic');
    var layout = require('../../util/layout');
P
pah100 已提交
6
    var DataDiffer = require('../../data/DataDiffer');
P
pah100 已提交
7 8
    var modelUtil = require('../../util/model');
    var helper = require('./helper');
P
pah100 已提交
9
    var parsePercent = require('../../util/number').parsePercent;
P
pah100 已提交
10
    var Breadcrumb = require('./Breadcrumb');
P
pah100 已提交
11 12 13 14
    var RoamController = require('../../component/helper/RoamController');
    var BoundingRect = require('zrender/core/BoundingRect');
    var matrix = require('zrender/core/matrix');
    var bind = zrUtil.bind;
P
pah100 已提交
15 16 17
    var Group = graphic.Group;
    var Rect = graphic.Rect;

P
pah100 已提交
18
    var ANIMATION_DURATION = 600;
P
pah100 已提交
19 20 21
    var EASING = 'cubicOut';
    var DRAG_THRESHOLD = 3;

P
pah100 已提交
22 23 24 25 26 27 28
    return require('../../echarts').extendChartView({

        type: 'treemap',

        /**
         * @override
         */
P
pah100 已提交
29
        init: function (o, api) {
P
pah100 已提交
30

P
pah100 已提交
31 32 33 34
            /**
             * @private
             * @type {module:zrender/container/Group}
             */
P
pah100 已提交
35
            this._containerGroup;
P
pah100 已提交
36 37 38 39 40

            /**
             * @private
             * @type {Object.<string, Array.<module:zrender/container/Group>>}
             */
P
pah100 已提交
41
            this._storage = createStorage();
P
pah100 已提交
42

P
pah100 已提交
43 44 45 46 47
            /**
             * @private
             * @type {module:echarts/data/Tree}
             */
            this._oldTree;
P
pah100 已提交
48 49 50 51 52 53

            /**
             * @private
             * @type {module:echarts/chart/treemap/Breadcrumb}
             */
            this._breadcrumb;
P
pah100 已提交
54 55 56 57 58 59 60 61

            /**
             * @private
             * @type {module:echarts/component/helper/RoamController}
             */
            this._controller;

            /**
P
pah100 已提交
62
             * 'ready', 'animating'
P
pah100 已提交
63 64 65
             * @private
             */
            this._state = 'ready';
P
pah100 已提交
66 67 68 69 70 71

            /**
             * @readOnly
             * @type {Object} {x, y, width, height}
             */
            this.positionInfo;
P
pah100 已提交
72 73 74 75 76 77

            /**
             * @private
             * @type {boolean}
             */
            this._mayClick;
P
pah100 已提交
78 79 80 81 82
        },

        /**
         * @override
         */
P
pah100 已提交
83 84 85 86 87
        render: function (seriesModel, ecModel, api, payload) {
            if (helper.irrelevant(payload, seriesModel)) {
                return;
            }

P
pah100 已提交
88
            this.seriesModel = seriesModel;
P
pah100 已提交
89
            this.api = api;
P
pah100 已提交
90
            this.ecModel = ecModel;
P
pah100 已提交
91

P
pah100 已提交
92 93
            var thisTree = seriesModel.getData().tree;
            var containerGroup = this._containerGroup;
P
pah100 已提交
94
            var containerSize = seriesModel.containerSize;
P
pah100 已提交
95

P
pah100 已提交
96
            if (!containerGroup) {
P
pah100 已提交
97 98
                // FIXME
                // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
P
pah100 已提交
99 100
                containerGroup = this._containerGroup = new Group();
                this._initEvents(containerGroup);
P
pah100 已提交
101
                this.group.add(containerGroup);
P
pah100 已提交
102
            }
P
pah100 已提交
103

P
pah100 已提交
104
            var positionInfo = this.positionInfo = layout.parsePositionInfo(
P
pah100 已提交
105 106 107 108
                {
                    x: seriesModel.get('x'),
                    y: seriesModel.get('y'),
                    x2: seriesModel.get('x2'),
P
pah100 已提交
109 110 111
                    y2: seriesModel.get('y2'),
                    width: containerSize[0],
                    height: containerSize[1]
P
pah100 已提交
112 113 114 115 116 117
                },
                {
                    width: api.getWidth(),
                    height: api.getHeight()
                }
            );
P
pah100 已提交
118
            containerGroup.position = [positionInfo.x, positionInfo.y];
P
pah100 已提交
119

P
pah100 已提交
120
            var lastShapes = this._doRender(thisTree, containerGroup, seriesModel);
P
pah100 已提交
121 122 123 124 125

            var targetInfo = helper.retrieveTargetNodeInfo(payload, seriesModel);
            var viewRect = payload && payload.type === 'treemapRender' && payload.viewRect;

            this._positionRoot(containerGroup, positionInfo, thisTree.root, viewRect, targetInfo);
P
pah100 已提交
126

P
pah100 已提交
127
            this._doAnimation(payload, containerGroup, lastShapes);
P
pah100 已提交
128

P
pah100 已提交
129
            this._initController(api);
P
pah100 已提交
130 131

            this._renderBreadcrumb(seriesModel, api, targetInfo);
P
pah100 已提交
132 133 134 135 136 137 138 139
        },

        /**
         * @private
         */
        _doRender: function (thisTree, containerGroup, seriesModel) {
            var oldTree = this._oldTree;

P
pah100 已提交
140
            // Clear last shape records.
P
pah100 已提交
141 142
            var lastShapes = createStorage();
            var thisStorage = createStorage();
P
pah100 已提交
143
            var oldStorage = this._storage;
P
pah100 已提交
144
            var renderNode = bind(this._renderNode, this);
P
pah100 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
            var viewRoot = seriesModel.getViewRoot();

            dualTravel(
                thisTree.root ? [thisTree.root] : [],
                (oldTree && oldTree.root) ? [oldTree.root] : [],
                containerGroup,
                thisTree === oldTree || !oldTree,
                viewRoot === thisTree.root
            );

            // Process all removing.
            clearStorage(oldStorage);

            this._oldTree = thisTree;
            this._storage = thisStorage;

P
pah100 已提交
161
            return lastShapes;
P
pah100 已提交
162

P
pah100 已提交
163 164 165 166 167 168
            function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, inView) {
                // When 'render' is triggered by action,
                // 'this' and 'old' may be the same tree,
                // we use rawIndex in that case.
                if (sameTree) {
                    oldViewChildren = thisViewChildren;
P
pah100 已提交
169
                    zrUtil.each(thisViewChildren, function (child, index) {
P
pah100 已提交
170
                        !child.isRemoved() && processNode(index, index);
P
pah100 已提交
171 172
                    });
                }
P
pah100 已提交
173 174
                // Diff hierarchically (diff only in each subtree, but not whole).
                // because, consistency of view is important.
P
pah100 已提交
175
                else {
P
pah100 已提交
176 177 178
                    (new DataDiffer(oldViewChildren, thisViewChildren, getKey))
                        .add(processNode)
                        .update(processNode)
179 180
                        .remove(zrUtil.curry(processNode, null))
                        .execute();
P
pah100 已提交
181 182 183 184 185
                }

                function getKey(node) {
                    // Identify by name or raw index.
                    return node.name != null ? node.name : node.getRawIndex();
P
pah100 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199
                }

                function processNode(newIndex, oldIndex) {
                    var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
                    var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;

                    // Whether under viewRoot.
                    var subInView = inView || thisNode === viewRoot;
                    // If not under viewRoot, only remove.
                    if (!subInView) {
                        thisNode = null;
                    }

                    var group = renderNode(
P
pah100 已提交
200
                        thisNode, oldNode, parentGroup, thisStorage, oldStorage, lastShapes
P
pah100 已提交
201 202 203 204 205
                    );
                    dualTravel(
                        thisNode && thisNode.viewChildren || [],
                        oldNode && oldNode.viewChildren || [],
                        group,
P
pah100 已提交
206
                        sameTree,
P
pah100 已提交
207 208 209 210
                        subInView
                    );
                }
            }
P
pah100 已提交
211 212 213 214 215 216 217 218

            function clearStorage(storage) {
                storage && zrUtil.each(storage, function (store) {
                    zrUtil.each(store, function (shape) {
                        shape && shape.parent && shape.parent.remove(shape);
                    });
                });
            }
P
pah100 已提交
219 220 221 222 223
        },

        /**
         * @private
         */
P
pah100 已提交
224
        _renderNode: function (thisNode, oldNode, parentGroup, thisStorage, oldStorage, lastShapes) {
P
pah100 已提交
225 226 227 228 229 230 231 232
            var thisRawIndex = thisNode && thisNode.getRawIndex();
            var oldRawIndex = oldNode && oldNode.getRawIndex();

            if (!thisNode) {
                return;
            }

            var layout = thisNode.getLayout();
P
pah100 已提交
233 234 235
            var thisWidth = layout.width;
            var thisHeight = layout.height;

P
pah100 已提交
236 237
            // Node group
            var group = giveGraphic('nodeGroup', Group, 'position');
P
pah100 已提交
238
            parentGroup.add(group);
P
pah100 已提交
239
            group.position = [layout.x, layout.y];
P
pah100 已提交
240

P
pah100 已提交
241
            // Background
P
pah100 已提交
242 243
            var bg = giveGraphic('background', Rect, 'shape');
            bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
P
pah100 已提交
244
            bg.setStyle({fill: thisNode.getVisual('borderColor', true)});
P
pah100 已提交
245
            group.add(bg);
P
pah100 已提交
246 247

            var thisViewChildren = thisNode.viewChildren;
P
pah100 已提交
248 249

            // No children, render content.
P
pah100 已提交
250
            if (!thisViewChildren || !thisViewChildren.length) {
P
pah100 已提交
251
                var borderWidth = layout.borderWidth;
P
pah100 已提交
252

P
pah100 已提交
253 254 255
                var content = giveGraphic('content', Rect, 'shape');
                var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
                var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
P
pah100 已提交
256
                var labelModel = thisNode.getModel('label.normal');
P
pah100 已提交
257 258 259
                var textStyleModel = thisNode.getModel('label.normal.textStyle');
                var text = thisNode.getModel().get('name');
                var textRect = textStyleModel.getTextRect(text);
P
pah100 已提交
260 261 262 263 264 265 266 267
                var showLabel = labelModel.get('show');

                if (!showLabel
                    || (
                        showLabel !== 'always'
                        && (textRect.width > contentWidth || textRect.height > contentHeight)
                    )
                ) {
P
pah100 已提交
268 269 270
                    text = '';
                }

P
pah100 已提交
271 272 273 274
                // For tooltip.
                content.dataIndex = thisNode.dataIndex;
                content.seriesIndex = this.seriesModel.seriesIndex;

L
lang 已提交
275
                content.culling = true;
P
pah100 已提交
276 277 278
                content.setShape({
                    x: borderWidth,
                    y: borderWidth,
P
pah100 已提交
279 280
                    width: contentWidth,
                    height: contentHeight
P
pah100 已提交
281 282
                });
                content.setStyle({
P
pah100 已提交
283 284
                    fill: thisNode.getVisual('color', true),
                    text: text,
P
pah100 已提交
285
                    textPosition: this._getTextPosition(labelModel, thisWidth, thisHeight),
P
pah100 已提交
286 287 288
                    textFill: textStyleModel.get('color'),
                    textAlign: textStyleModel.get('align'),
                    textFont: textStyleModel.getFont()
P
pah100 已提交
289 290
                });
                group.add(content);
P
pah100 已提交
291 292
            }

P
pah100 已提交
293 294
            return group;

P
pah100 已提交
295
            function giveGraphic(storage, Ctor, type) {
P
pah100 已提交
296 297 298 299 300
                var shape = oldRawIndex != null && oldStorage && oldStorage[storage][oldRawIndex];

                if (shape) {
                    // Remove from oldStorage
                    oldStorage && (oldStorage[storage][oldRawIndex] = null);
P
pah100 已提交
301 302 303
                    var lastCfg = lastShapes[storage][thisRawIndex] = {};
                    lastCfg[type] = type === 'position'
                         ? shape.position.slice() : zrUtil.extend({}, shape.shape);
P
pah100 已提交
304 305 306 307 308 309 310
                }
                else {
                    shape = new Ctor();
                }

                // Set to thisStorage
                return thisStorage[storage][thisRawIndex] = shape;
P
pah100 已提交
311
            }
P
pah100 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        },

        /**
         * @private
         */
        _getTextPosition: function (labelModel, nodeWidth, nodeHeight) {
            var position = labelModel.get('position');

            if (zrUtil.isArray(position)) {
                position = [
                    parsePercent(position[0], nodeWidth),
                    parsePercent(position[1], nodeHeight)
                ];
            }
            return position;
P
pah100 已提交
327 328
        },

P
pah100 已提交
329 330 331
        /**
         * @private
         */
P
pah100 已提交
332
        _doAnimation: function (payload, containerGroup, lastShapes) {
P
pah100 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
            if (!this.ecModel.get('animation')
                || (payload && payload.type === 'treemapRender')
            ) {
                return;
            }

            var animationCount = 0;
            var that = this;

            zrUtil.each(this._storage, function (shapes, key) {
                zrUtil.each(shapes, function (shape, index) {
                    var last = lastShapes[key][index];
                    if (!last) {
                        return;
                    }
                    if (last.position) {
                        var target = shape.position.slice();
                        shape.position = last.position;
                        shape.animateTo({position: target}, ANIMATION_DURATION, EASING, done);
                        animationCount++;
                    }
                    else if (last.shape) {
                        var target = zrUtil.extend({}, shape.shape);
                        shape.setShape(last.shape);
                        shape.animateTo({shape: target}, ANIMATION_DURATION, EASING, done);
                        animationCount++;
                    }
                });
            });

            if (animationCount) {
                this._state = 'animating';
            }
P
pah100 已提交
366

P
pah100 已提交
367 368 369 370 371 372 373 374 375 376 377
            function done() {
                animationCount--;
                if (!animationCount) {
                    that._state = 'ready';
                }
            }
        },

        /**
         * @private
         */
P
pah100 已提交
378
        _initController: function (api) {
P
pah100 已提交
379 380 381 382 383
            var controller = this._controller;

            // Init controller.
            if (!controller) {
                controller = this._controller = new RoamController(api.getZr());
P
pah100 已提交
384 385 386 387 388 389 390
                controller.on('pan', bind(handle, this, this._onPan));
                controller.on('zoom', bind(handle, this, this._onZoom));
            }

            function handle(handler) {
                this._mayClick = false;
                return handler.apply(this, Array.prototype.slice.call(arguments, 1));
P
pah100 已提交
391 392
            }

P
pah100 已提交
393 394 395
            controller.rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());

            if (!this.seriesModel.get('roam')) {
P
pah100 已提交
396 397 398 399
                controller.off('pan').off('zoom');
                this._controller = null;
                return;
            }
P
pah100 已提交
400
        },
P
pah100 已提交
401

P
pah100 已提交
402 403 404 405 406 407 408 409 410 411 412 413
        /**
         * @private
         */
        _onPan: function (dx, dy) {
            if (this._state !== 'animating'
                && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
            ) {
                // These param must not be cached.
                var seriesModel = this.seriesModel;
                var root = seriesModel.getData().tree.root;
                if (!root) {
                    return;
P
pah100 已提交
414
                }
P
pah100 已提交
415 416 417 418 419 420 421 422
                var rootGroup = this._storage.nodeGroup[root.getRawIndex()];
                var pos = rootGroup.position;
                pos[0] += dx;
                pos[1] += dy;
                rootGroup.dirty();

                // Update breadcrumb when drag move.
                this._renderBreadcrumb(seriesModel, this.api);
P
pah100 已提交
423
            }
P
pah100 已提交
424
        },
P
pah100 已提交
425

P
pah100 已提交
426 427 428 429
        /**
         * @private
         */
        _onZoom: function (scale, mouseX, mouseY) {
P
pah100 已提交
430
            if (this._state !== 'animating' && !this._controller.isDragging()) {
P
pah100 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
                // These param must not be cached.
                var rect = this._containerGroup.getBoundingRect();
                var positionInfo = this.positionInfo;

                mouseX -= positionInfo.x;
                mouseY -= positionInfo.y;
                // Recalculate bounding rect.
                var m = matrix.create();
                matrix.translate(m, m, [-mouseX, -mouseY]);
                matrix.scale(m, m, [scale, scale]);
                matrix.translate(m, m, [mouseX, mouseY]);

                rect.applyTransform(m);

                this.api.dispatch({
                    type: 'treemapRender',
                    from: this.uid,
                    seriesId: this.seriesModel.uid,
                    viewRect: {
                        x: rect.x, y: rect.y, width: rect.width, height: rect.height
                    }
                });
P
pah100 已提交
453 454 455 456 457 458
            }
        },

        /**
         * @private
         */
P
pah100 已提交
459
        _initEvents: function (containerGroup) {
P
pah100 已提交
460 461 462 463 464 465
            // FIXME
            // 不用click以及silent的原因是,animate时视图设置silent true来避免click生效,
            // 但是animate中,按下鼠标,animate结束后(silent设回为false)松开鼠标,
            // 还是会触发click,期望是不触发。
            var that = this;

P
pah100 已提交
466 467 468
            // Mousedown occurs when drag start, and mouseup occurs when drag end,
            // click event should not be triggered in that case.

P
pah100 已提交
469
            containerGroup.on('mousedown', function (e) {
P
pah100 已提交
470
                that._state === 'ready' && (that._mayClick = true);
P
pah100 已提交
471 472
            });
            containerGroup.on('mouseup', function (e) {
P
pah100 已提交
473 474 475
                if (that._mayClick) {
                    that._mayClick = false;
                    that._state === 'ready' && onClick(e);
P
pah100 已提交
476 477 478 479 480 481 482 483 484 485 486
                }
            });

            function onClick(e) {
                var targetInfo = that.findTarget(e.offsetX, e.offsetY);
                if (targetInfo) {
                    that._zoomToNode(targetInfo);
                }
            }
        },

P
pah100 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        /**
         * @private
         */
        _renderBreadcrumb: function (seriesModel, api, targetInfo) {
            if (!targetInfo) {
                // Find breadcrumb tail on center of containerGroup.
                targetInfo = this.findTarget(api.getWidth() / 2, api.getHeight() / 2);

                if (!targetInfo) {
                    targetInfo = {node: seriesModel.getData().tree.root};
                }
            }

            (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group, onSelect)))
                .render(seriesModel, api, targetInfo.node);

            var that = this;
            function onSelect(node) {
                that._zoomToNode({node: node});
            }
        },

P
pah100 已提交
509 510 511 512
        /**
         * @override
         */
        remove: function () {
P
pah100 已提交
513 514 515
            this._containerGroup.removeAll();
            this._storage = createStorage();
            this._state = 'ready';
P
pah100 已提交
516
            this._breadcrumb && this._breadcrumb.remove();
P
pah100 已提交
517 518
        },

P
pah100 已提交
519 520 521 522
        /**
         * @private
         */
        _zoomToNode: function (targetInfo) {
P
pah100 已提交
523
            this.api.dispatch({
P
pah100 已提交
524
                type: 'treemapZoomToNode',
P
pah100 已提交
525
                from: this.uid,
P
pah100 已提交
526 527
                seriesId: this.seriesModel.uid,
                targetInfo: targetInfo
P
pah100 已提交
528 529 530 531 532
            });
        },

        /**
         * @public
P
pah100 已提交
533 534
         * @param {number} x Global coord x.
         * @param {number} y Global coord y.
P
pah100 已提交
535 536 537 538 539 540 541 542 543 544
         * @return {Object} info If not found, return undefined;
         * @return {number} info.node Target node.
         * @return {number} info.offsetX x refer to target node.
         * @return {number} info.offsetY y refer to target node.
         */
        findTarget: function (x, y) {
            var targetInfo;
            var viewRoot = this.seriesModel.getViewRoot();

            viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
545 546 547 548 549 550 551 552 553 554
                var bgShape = this._storage.background[node.getRawIndex()];
                var point = bgShape.transformCoordToLocal(x, y);
                var shape = bgShape.shape;

                // For performance consideration, dont use 'getBoundingRect'.
                if (shape.x <= point[0]
                    && point[0] <= shape.x + shape.width
                    && shape.y <= point[1]
                    && point[1] <= shape.y + shape.height
                ) {
P
pah100 已提交
555 556 557 558 559 560 561 562
                    targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
                }
                else {
                    return false; // Suppress visit subtree.
                }
            }, this);

            return targetInfo;
P
pah100 已提交
563 564 565 566 567
        },

        /**
         * @private
         */
P
pah100 已提交
568
        _positionRoot: function(containerGroup, positionInfo, root, viewRect, targetInfo) {
P
pah100 已提交
569 570 571
            var nodeGroups = this._storage.nodeGroup;
            var rootGroup = nodeGroups[root.getRawIndex()];

P
pah100 已提交
572 573 574 575 576
            if (viewRect) {
                rootGroup.position = [viewRect.x, viewRect.y];
                return;
            }

P
pah100 已提交
577 578 579 580 581
            if (!targetInfo) {
                rootGroup.position = [0, 0];
                return;
            }

P
pah100 已提交
582
            // If targetInfo is fetched by 'retrieveTargetNodeInfo',
P
pah100 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595
            // old tree and new tree are the same tree,
            // so we can use raw index of targetInfo.node to find shape from storage.

            var targetNode = targetInfo.node;

            var targetGroup = nodeGroups[targetNode.getRawIndex()];

            if (!targetGroup) {
                rootGroup.position = [0, 0];
                return;
            }

            var targetRect = targetGroup.getBoundingRect();
596
            var targetCenter = graphic.transformCoordToAncestor(
P
pah100 已提交
597 598 599
                [targetRect.width / 2, targetRect.height / 2], targetGroup, containerGroup
            );
            rootGroup.position = [
P
pah100 已提交
600 601
                positionInfo.width / 2 - targetCenter[0],
                positionInfo.height / 2 - targetCenter[1]
P
pah100 已提交
602
            ];
P
pah100 已提交
603 604 605
        }

    });
P
pah100 已提交
606

P
pah100 已提交
607 608 609 610
    function createStorage() {
        return {nodeGroup: [], background: [], content: []};
    }

P
pah100 已提交
611
});