-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
barGrid.ts
614 lines (534 loc) · 22.9 KB
/
barGrid.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { each, defaults, keys } from 'zrender/src/core/util';
import { parsePercent } from '../util/number';
import { isDimensionStacked } from '../data/helper/dataStackHelper';
import createRenderPlanner from '../chart/helper/createRenderPlanner';
import BarSeriesModel from '../chart/bar/BarSeries';
import Axis2D from '../coord/cartesian/Axis2D';
import GlobalModel from '../model/Global';
import type Cartesian2D from '../coord/cartesian/Cartesian2D';
import { StageHandler, Dictionary } from '../util/types';
import { createFloat32Array } from '../util/vendor';
const STACK_PREFIX = '__ec_stack_';
function getSeriesStackId(seriesModel: BarSeriesModel): string {
return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
}
function getAxisKey(axis: Axis2D): string {
return axis.dim + axis.index;
}
interface LayoutSeriesInfo {
bandWidth: number
barWidth: number
barMaxWidth: number
barMinWidth: number
barGap: number | string
barCategoryGap: number | string
axisKey: string
stackId: string
}
interface StackInfo {
width: number
maxWidth: number
minWidth?: number
}
/**
* {
* [coordSysId]: {
* [stackId]: {bandWidth, offset, width}
* }
* }
*/
type BarWidthAndOffset = Dictionary<Dictionary<{
bandWidth: number
offset: number
offsetCenter: number
width: number
}>>;
export interface BarGridLayoutOptionForCustomSeries {
count: number
barWidth?: number | string
barMaxWidth?: number | string
barMinWidth?: number | string
barGap?: number | string
barCategoryGap?: number | string
}
interface LayoutOption extends BarGridLayoutOptionForCustomSeries {
axis: Axis2D
}
export type BarGridLayoutResult = BarWidthAndOffset[string][string][];
/**
* @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
*/
export function getLayoutOnAxis(opt: LayoutOption): BarGridLayoutResult {
const params: LayoutSeriesInfo[] = [];
const baseAxis = opt.axis;
const axisKey = 'axis0';
if (baseAxis.type !== 'category') {
return;
}
const bandWidth = baseAxis.getBandWidth();
for (let i = 0; i < opt.count || 0; i++) {
params.push(defaults({
bandWidth: bandWidth,
axisKey: axisKey,
stackId: STACK_PREFIX + i
}, opt) as LayoutSeriesInfo);
}
const widthAndOffsets = doCalBarWidthAndOffset(params);
const result = [];
for (let i = 0; i < opt.count; i++) {
const item = widthAndOffsets[axisKey][STACK_PREFIX + i];
item.offsetCenter = item.offset + item.width / 2;
result.push(item);
}
return result;
}
export function prepareLayoutBarSeries(seriesType: string, ecModel: GlobalModel): BarSeriesModel[] {
const seriesModels: BarSeriesModel[] = [];
ecModel.eachSeriesByType(seriesType, function (seriesModel: BarSeriesModel) {
// Check series coordinate, do layout for cartesian2d only
if (isOnCartesian(seriesModel)) {
seriesModels.push(seriesModel);
}
});
return seriesModels;
}
/**
* Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
* values.
* This works for time axes, value axes, and log axes.
* For a single time axis, return value is in the form like
* {'x_0': [1000000]}.
* The value of 1000000 is in milliseconds.
*/
function getValueAxesMinGaps(barSeries: BarSeriesModel[]) {
/**
* Map from axis.index to values.
* For a single time axis, axisValues is in the form like
* {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
* Items in axisValues[x], e.g. 1495555200000, are time values of all
* series.
*/
const axisValues: Dictionary<number[]> = {};
each(barSeries, function (seriesModel) {
const cartesian = seriesModel.coordinateSystem as Cartesian2D;
const baseAxis = cartesian.getBaseAxis();
if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
return;
}
const data = seriesModel.getData();
const key = baseAxis.dim + '_' + baseAxis.index;
const dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
const store = data.getStore();
for (let i = 0, cnt = store.count(); i < cnt; ++i) {
const value = store.get(dimIdx, i) as number;
if (!axisValues[key]) {
// No previous data for the axis
axisValues[key] = [value];
}
else {
// No value in previous series
axisValues[key].push(value);
}
// Ignore duplicated time values in the same axis
}
});
const axisMinGaps: Dictionary<number> = {};
for (const key in axisValues) {
if (axisValues.hasOwnProperty(key)) {
const valuesInAxis = axisValues[key];
if (valuesInAxis) {
// Sort axis values into ascending order to calculate gaps
valuesInAxis.sort(function (a, b) {
return a - b;
});
let min = null;
for (let j = 1; j < valuesInAxis.length; ++j) {
const delta = valuesInAxis[j] - valuesInAxis[j - 1];
if (delta > 0) {
// Ignore 0 delta because they are of the same axis value
min = min === null ? delta : Math.min(min, delta);
}
}
// Set to null if only have one data
axisMinGaps[key] = min;
}
}
}
return axisMinGaps;
}
export function makeColumnLayout(barSeries: BarSeriesModel[]) {
const axisMinGaps = getValueAxesMinGaps(barSeries);
const seriesInfoList: LayoutSeriesInfo[] = [];
each(barSeries, function (seriesModel) {
const cartesian = seriesModel.coordinateSystem as Cartesian2D;
const baseAxis = cartesian.getBaseAxis();
const axisExtent = baseAxis.getExtent();
let bandWidth;
if (baseAxis.type === 'category') {
bandWidth = baseAxis.getBandWidth();
}
else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
const key = baseAxis.dim + '_' + baseAxis.index;
const minGap = axisMinGaps[key];
const extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
const scale = baseAxis.scale.getExtent();
const scaleSpan = Math.abs(scale[1] - scale[0]);
bandWidth = minGap
? extentSpan / scaleSpan * minGap
: extentSpan; // When there is only one data value
}
else {
const data = seriesModel.getData();
bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
}
const barWidth = parsePercent(
seriesModel.get('barWidth'), bandWidth
);
const barMaxWidth = parsePercent(
seriesModel.get('barMaxWidth'), bandWidth
);
const barMinWidth = parsePercent(
// barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
// the auto-calculated bar width might be less than 0.5 / 1.
seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth
);
const barGap = seriesModel.get('barGap');
const barCategoryGap = seriesModel.get('barCategoryGap');
seriesInfoList.push({
bandWidth: bandWidth,
barWidth: barWidth,
barMaxWidth: barMaxWidth,
barMinWidth: barMinWidth,
barGap: barGap,
barCategoryGap: barCategoryGap,
axisKey: getAxisKey(baseAxis),
stackId: getSeriesStackId(seriesModel)
});
});
return doCalBarWidthAndOffset(seriesInfoList);
}
function doCalBarWidthAndOffset(seriesInfoList: LayoutSeriesInfo[]) {
interface ColumnOnAxisInfo {
bandWidth: number
remainedWidth: number
autoWidthCount: number
categoryGap: number | string
gap: number | string
stacks: Dictionary<StackInfo>
}
// Columns info on each category axis. Key is cartesian name
const columnsMap: Dictionary<ColumnOnAxisInfo> = {};
each(seriesInfoList, function (seriesInfo, idx) {
const axisKey = seriesInfo.axisKey;
const bandWidth = seriesInfo.bandWidth;
const columnsOnAxis: ColumnOnAxisInfo = columnsMap[axisKey] || {
bandWidth: bandWidth,
remainedWidth: bandWidth,
autoWidthCount: 0,
categoryGap: null,
gap: '20%',
stacks: {}
};
const stacks = columnsOnAxis.stacks;
columnsMap[axisKey] = columnsOnAxis;
const stackId = seriesInfo.stackId;
if (!stacks[stackId]) {
columnsOnAxis.autoWidthCount++;
}
stacks[stackId] = stacks[stackId] || {
width: 0,
maxWidth: 0
};
// Caution: In a single coordinate system, these barGrid attributes
// will be shared by series. Consider that they have default values,
// only the attributes set on the last series will work.
// Do not change this fact unless there will be a break change.
let barWidth = seriesInfo.barWidth;
if (barWidth && !stacks[stackId].width) {
// See #6312, do not restrict width.
stacks[stackId].width = barWidth;
barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
columnsOnAxis.remainedWidth -= barWidth;
}
const barMaxWidth = seriesInfo.barMaxWidth;
barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
const barMinWidth = seriesInfo.barMinWidth;
barMinWidth && (stacks[stackId].minWidth = barMinWidth);
const barGap = seriesInfo.barGap;
(barGap != null) && (columnsOnAxis.gap = barGap);
const barCategoryGap = seriesInfo.barCategoryGap;
(barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
});
const result: BarWidthAndOffset = {};
each(columnsMap, function (columnsOnAxis, coordSysName) {
result[coordSysName] = {};
const stacks = columnsOnAxis.stacks;
const bandWidth = columnsOnAxis.bandWidth;
let categoryGapPercent = columnsOnAxis.categoryGap;
if (categoryGapPercent == null) {
const columnCount = keys(stacks).length;
// More columns in one group
// the spaces between group is smaller. Or the column will be too thin.
categoryGapPercent = Math.max((35 - columnCount * 4), 15) + '%';
}
const categoryGap = parsePercent(categoryGapPercent, bandWidth);
const barGapPercent = parsePercent(columnsOnAxis.gap, 1);
let remainedWidth = columnsOnAxis.remainedWidth;
let autoWidthCount = columnsOnAxis.autoWidthCount;
let autoWidth = (remainedWidth - categoryGap)
/ (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
autoWidth = Math.max(autoWidth, 0);
// Find if any auto calculated bar exceeded maxBarWidth
each(stacks, function (column) {
const maxWidth = column.maxWidth;
const minWidth = column.minWidth;
if (!column.width) {
let finalWidth = autoWidth;
if (maxWidth && maxWidth < finalWidth) {
finalWidth = Math.min(maxWidth, remainedWidth);
}
// `minWidth` has higher priority. `minWidth` decide that whether the
// bar is able to be visible. So `minWidth` should not be restricted
// by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
// the extreme cases for `value` axis, bars are allowed to overlap
// with each other if `minWidth` specified.
if (minWidth && minWidth > finalWidth) {
finalWidth = minWidth;
}
if (finalWidth !== autoWidth) {
column.width = finalWidth;
remainedWidth -= finalWidth + barGapPercent * finalWidth;
autoWidthCount--;
}
}
else {
// `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
// CSS does. Because barWidth can be a percent value, where
// `barMaxWidth` can be used to restrict the final width.
let finalWidth = column.width;
if (maxWidth) {
finalWidth = Math.min(finalWidth, maxWidth);
}
// `minWidth` has higher priority, as described above
if (minWidth) {
finalWidth = Math.max(finalWidth, minWidth);
}
column.width = finalWidth;
remainedWidth -= finalWidth + barGapPercent * finalWidth;
autoWidthCount--;
}
});
// Recalculate width again
autoWidth = (remainedWidth - categoryGap)
/ (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
autoWidth = Math.max(autoWidth, 0);
let widthSum = 0;
let lastColumn: StackInfo;
each(stacks, function (column, idx) {
if (!column.width) {
column.width = autoWidth;
}
lastColumn = column;
widthSum += column.width * (1 + barGapPercent);
});
if (lastColumn) {
widthSum -= lastColumn.width * barGapPercent;
}
let offset = -widthSum / 2;
each(stacks, function (column, stackId) {
result[coordSysName][stackId] = result[coordSysName][stackId] || {
bandWidth: bandWidth,
offset: offset,
width: column.width
} as BarWidthAndOffset[string][string];
offset += column.width * (1 + barGapPercent);
});
});
return result;
}
/**
* @param barWidthAndOffset The result of makeColumnLayout
* @param seriesModel If not provided, return all.
* @return {stackId: {offset, width}} or {offset, width} if seriesModel provided.
*/
function retrieveColumnLayout(barWidthAndOffset: BarWidthAndOffset, axis: Axis2D): typeof barWidthAndOffset[string];
// eslint-disable-next-line max-len
function retrieveColumnLayout(barWidthAndOffset: BarWidthAndOffset, axis: Axis2D, seriesModel: BarSeriesModel): typeof barWidthAndOffset[string][string];
function retrieveColumnLayout(
barWidthAndOffset: BarWidthAndOffset,
axis: Axis2D,
seriesModel?: BarSeriesModel
) {
if (barWidthAndOffset && axis) {
const result = barWidthAndOffset[getAxisKey(axis)];
if (result != null && seriesModel != null) {
return result[getSeriesStackId(seriesModel)];
}
return result;
}
}
export {retrieveColumnLayout};
export function layout(seriesType: string, ecModel: GlobalModel) {
const seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
const barWidthAndOffset = makeColumnLayout(seriesModels);
each(seriesModels, function (seriesModel) {
const data = seriesModel.getData();
const cartesian = seriesModel.coordinateSystem as Cartesian2D;
const baseAxis = cartesian.getBaseAxis();
const stackId = getSeriesStackId(seriesModel);
const columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
const columnOffset = columnLayoutInfo.offset;
const columnWidth = columnLayoutInfo.width;
data.setLayout({
bandWidth: columnLayoutInfo.bandWidth,
offset: columnOffset,
size: columnWidth
});
});
}
// TODO: Do not support stack in large mode yet.
export function createProgressiveLayout(seriesType: string): StageHandler {
return {
seriesType,
plan: createRenderPlanner(),
reset: function (seriesModel: BarSeriesModel) {
if (!isOnCartesian(seriesModel)) {
return;
}
const data = seriesModel.getData();
const cartesian = seriesModel.coordinateSystem as Cartesian2D;
const baseAxis = cartesian.getBaseAxis();
const valueAxis = cartesian.getOtherAxis(baseAxis);
const valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
const baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
const drawBackground = seriesModel.get('showBackground', true);
const valueDim = data.mapDimension(valueAxis.dim);
const stackResultDim = data.getCalculationInfo('stackResultDimension');
const stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
const isValueAxisH = valueAxis.isHorizontal();
const valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
const isLarge = isInLargeMode(seriesModel);
const barMinHeight = seriesModel.get('barMinHeight') || 0;
const stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim);
// Layout info.
const columnWidth = data.getLayout('size');
const columnOffset = data.getLayout('offset');
return {
progress: function (params, data) {
const count = params.count;
const largePoints = isLarge && createFloat32Array(count * 3);
const largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
const largeDataIndices = isLarge && createFloat32Array(count);
const coordLayout = cartesian.master.getRect();
const bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
let dataIndex;
const store = data.getStore();
let idxOffset = 0;
while ((dataIndex = params.next()) != null) {
const value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
const baseValue = store.get(baseDimIdx, dataIndex) as number;
let baseCoord = valueAxisStart;
let stackStartValue;
// Because of the barMinHeight, we can not use the value in
// stackResultDimension directly.
if (stacked) {
stackStartValue = +value - (store.get(valueDimIdx, dataIndex) as number);
}
let x;
let y;
let width;
let height;
if (isValueAxisH) {
const coord = cartesian.dataToPoint([value, baseValue]);
if (stacked) {
const startCoord = cartesian.dataToPoint([stackStartValue, baseValue]);
baseCoord = startCoord[0];
}
x = baseCoord;
y = coord[1] + columnOffset;
width = coord[0] - baseCoord;
height = columnWidth;
if (Math.abs(width) < barMinHeight) {
width = (width < 0 ? -1 : 1) * barMinHeight;
}
}
else {
const coord = cartesian.dataToPoint([baseValue, value]);
if (stacked) {
const startCoord = cartesian.dataToPoint([baseValue, stackStartValue]);
baseCoord = startCoord[1];
}
x = coord[0] + columnOffset;
y = baseCoord;
width = columnWidth;
height = coord[1] - baseCoord;
if (Math.abs(height) < barMinHeight) {
// Include zero to has a positive bar
height = (height <= 0 ? -1 : 1) * barMinHeight;
}
}
if (!isLarge) {
data.setItemLayout(dataIndex, { x, y, width, height });
}
else {
largePoints[idxOffset] = x;
largePoints[idxOffset + 1] = y;
largePoints[idxOffset + 2] = isValueAxisH ? width : height;
if (largeBackgroundPoints) {
largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
largeBackgroundPoints[idxOffset + 2] = bgSize;
}
largeDataIndices[dataIndex] = dataIndex;
}
idxOffset += 3;
}
if (isLarge) {
data.setLayout({
largePoints,
largeDataIndices,
largeBackgroundPoints,
valueAxisHorizontal: isValueAxisH
});
}
}
};
}
};
}
function isOnCartesian(seriesModel: BarSeriesModel) {
return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
}
function isInLargeMode(seriesModel: BarSeriesModel) {
return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
}
// See cases in `test/bar-start.html` and `#7412`, `#8747`.
function getValueAxisStart(baseAxis: Axis2D, valueAxis: Axis2D) {
let startValue = valueAxis.model.get('startValue');
if (!startValue) {
startValue = 0;
}
return valueAxis.toGlobalCoord(
valueAxis.dataToCoord(
valueAxis.type === 'log'
? (startValue > 0 ? startValue : 1)
: startValue));
}