UNPKG

2.46 kBJavaScriptView Raw
1const isArray = require('@antv/util/src/type/isArray');
2const Adjust = require('./base');
3
4class Stack extends Adjust {
5
6 _initDefaultCfg() {
7 this.xField = null; // 调整对应的 x 方向对应的字段名称
8 this.yField = null; // 调整对应的 y 方向对应的字段名称
9 this.height = null; // 仅有一个维度调整时,总的高度
10 this.size = 10; // 单个点的大小
11 this.reverseOrder = false; // 是否反序进行层叠
12 this.adjustNames = [ 'y' ]; // Only support stack y
13 }
14
15 processOneDimStack(dataArray) {
16 const self = this;
17 const xField = self.xField;
18 const yField = self.yField || 'y';
19 const height = self.height;
20
21 const stackY = {};
22 // 如果层叠的顺序翻转
23 if (self.reverseOrder) {
24 dataArray = dataArray.slice(0).reverse();
25 }
26 for (let i = 0, len = dataArray.length; i < len; i++) {
27 const data = dataArray[i];
28 // cates
29 for (let j = 0, dataLen = data.length; j < dataLen; j++) {
30 const item = data[j];
31 const size = item.size || self.size;
32 const stackHeight = (size * 2) / height;
33 const x = item[xField];
34 if (!stackY[x]) {
35 stackY[x] = stackHeight / 2;
36 }
37 item[yField] = stackY[x];
38 stackY[x] += stackHeight;
39 }
40 }
41
42 }
43
44 processAdjust(dataArray) {
45 if (this.yField) {
46 this.processStack(dataArray);
47 } else {
48 this.processOneDimStack(dataArray);
49 }
50 }
51
52 processStack(dataArray) {
53 const self = this;
54 const xField = self.xField;
55 const yField = self.yField;
56 const count = dataArray.length;
57 const stackCache = {
58 positive: {},
59 negative: {}
60 };
61 // 层叠顺序翻转
62 if (self.reverseOrder) {
63 dataArray = dataArray.slice(0).reverse();
64 }
65 for (let i = 0; i < count; i++) {
66 const data = dataArray[i];
67 for (let j = 0, len = data.length; j < len; j++) {
68 const item = data[j];
69 const x = item[xField] || 0;
70 let y = item[yField] || 0;
71 const xkey = x.toString();
72 y = isArray(y) ? y[1] : y;
73 const direction = y >= 0 ? 'positive' : 'negative';
74 if (!stackCache[direction][xkey]) {
75 stackCache[direction][xkey] = 0;
76 }
77 item[yField] = [ stackCache[direction][xkey], y + stackCache[direction][xkey] ];
78 stackCache[direction][xkey] += y;
79 }
80 }
81 }
82}
83
84Adjust.Stack = Stack;
85module.exports = Stack;