-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathLineView.ts
1473 lines (1296 loc) · 50.3 KB
/
LineView.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*/
// FIXME step not support polar
import * as zrUtil from 'zrender/src/core/util';
import SymbolDraw from '../helper/SymbolDraw';
import SymbolClz from '../helper/Symbol';
import lineAnimationDiff from './lineAnimationDiff';
import * as graphic from '../../util/graphic';
import * as modelUtil from '../../util/model';
import { ECPolyline, ECPolygon } from './poly';
import ChartView from '../../view/Chart';
import { prepareDataCoordInfo, getStackedOnPoint } from './helper';
import { createGridClipPath, createPolarClipPath } from '../helper/createClipPathFromCoordSys';
import LineSeriesModel, { LineSeriesOption } from './LineSeries';
import type GlobalModel from '../../model/Global';
import type ExtensionAPI from '../../core/ExtensionAPI';
// TODO
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Polar from '../../coord/polar/Polar';
import type SeriesData from '../../data/SeriesData';
import type {
Payload,
Dictionary,
ColorString,
ECElement,
DisplayState,
LabelOption,
ParsedValue
} from '../../util/types';
import type OrdinalScale from '../../scale/Ordinal';
import type Axis2D from '../../coord/cartesian/Axis2D';
import { CoordinateSystemClipArea, isCoordinateSystemType } from '../../coord/CoordinateSystem';
import { setStatesStylesFromModel, setStatesFlag, toggleHoverEmphasis, SPECIAL_STATES } from '../../util/states';
import Model from '../../model/Model';
import { setLabelStyle, getLabelStatesModels, labelInner } from '../../label/labelStyle';
import { getDefaultLabel, getDefaultInterpolatedLabel } from '../helper/labelHelper';
import { getECData } from '../../util/innerStore';
import { createFloat32Array } from '../../util/vendor';
import { convertToColorString } from '../../util/format';
import { lerp } from 'zrender/src/tool/color';
import Element from 'zrender/src/Element';
type PolarArea = ReturnType<Polar['getArea']>;
type Cartesian2DArea = ReturnType<Cartesian2D['getArea']>;
interface SymbolExtended extends SymbolClz {
__temp: boolean
}
interface ColorStop {
offset: number
coord?: number
color: ColorString
}
function isPointsSame(points1: ArrayLike<number>, points2: ArrayLike<number>) {
if (points1.length !== points2.length) {
return;
}
for (let i = 0; i < points1.length; i++) {
if (points1[i] !== points2[i]) {
return;
}
}
return true;
}
function bboxFromPoints(points: ArrayLike<number>) {
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < points.length;) {
const x = points[i++];
const y = points[i++];
if (!isNaN(x)) {
minX = Math.min(x, minX);
maxX = Math.max(x, maxX);
}
if (!isNaN(y)) {
minY = Math.min(y, minY);
maxY = Math.max(y, maxY);
}
}
return [
[minX, minY],
[maxX, maxY]
];
}
function getBoundingDiff(points1: ArrayLike<number>, points2: ArrayLike<number>): number {
const [min1, max1] = bboxFromPoints(points1);
const [min2, max2] = bboxFromPoints(points2);
// Get a max value from each corner of two boundings.
return Math.max(
Math.abs(min1[0] - min2[0]),
Math.abs(min1[1] - min2[1]),
Math.abs(max1[0] - max2[0]),
Math.abs(max1[1] - max2[1])
);
}
function getSmooth(smooth: number | boolean) {
return zrUtil.isNumber(smooth) ? smooth : (smooth ? 0.5 : 0);
}
function getStackedOnPoints(
coordSys: Cartesian2D | Polar,
data: SeriesData,
dataCoordInfo: ReturnType<typeof prepareDataCoordInfo>
) {
if (!dataCoordInfo.valueDim) {
return [];
}
const len = data.count();
const points = createFloat32Array(len * 2);
for (let idx = 0; idx < len; idx++) {
const pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
points[idx * 2] = pt[0];
points[idx * 2 + 1] = pt[1];
}
return points;
}
/**
* Filter the null data and extend data for step considering `stepTurnAt`
*
* @param points data to convert, that may containing null
* @param basePoints base data to reference, used only for areaStyle points
* @param coordSys coordinate system
* @param stepTurnAt 'start' | 'end' | 'middle' | true
* @param connectNulls whether to connect nulls
* @returns converted point positions
*/
function turnPointsIntoStep(
points: ArrayLike<number>,
basePoints: ArrayLike<number> | null,
coordSys: Cartesian2D | Polar,
stepTurnAt: 'start' | 'end' | 'middle',
connectNulls: boolean
): number[] {
const baseAxis = coordSys.getBaseAxis();
const baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
const stepPoints: number[] = [];
let i = 0;
const stepPt: number[] = [];
const pt: number[] = [];
const nextPt: number[] = [];
const filteredPoints = [];
if (connectNulls) {
for (i = 0; i < points.length; i += 2) {
/**
* For areaStyle of stepped lines, `stackedOnPoints` should be
* filtered the same as `points` so that the base axis values
* should stay the same as the lines above. See #20021
*/
const reference = basePoints || points;
if (!isNaN(reference[i]) && !isNaN(reference[i + 1])) {
filteredPoints.push(points[i], points[i + 1]);
}
}
points = filteredPoints;
}
for (i = 0; i < points.length - 2; i += 2) {
nextPt[0] = points[i + 2];
nextPt[1] = points[i + 3];
pt[0] = points[i];
pt[1] = points[i + 1];
stepPoints.push(pt[0], pt[1]);
switch (stepTurnAt) {
case 'end':
stepPt[baseIndex] = nextPt[baseIndex];
stepPt[1 - baseIndex] = pt[1 - baseIndex];
stepPoints.push(stepPt[0], stepPt[1]);
break;
case 'middle':
const middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
const stepPt2 = [];
stepPt[baseIndex] = stepPt2[baseIndex] = middle;
stepPt[1 - baseIndex] = pt[1 - baseIndex];
stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
stepPoints.push(stepPt[0], stepPt[1]);
stepPoints.push(stepPt2[0], stepPt2[1]);
break;
default:
// default is start
stepPt[baseIndex] = pt[baseIndex];
stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
stepPoints.push(stepPt[0], stepPt[1]);
}
}
// Last points
stepPoints.push(points[i++], points[i++]);
return stepPoints;
}
/**
* Clip color stops to edge. Avoid creating too large gradients.
* Which may lead to blurry when GPU acceleration is enabled. See #15680
*
* The stops has been sorted from small to large.
*/
function clipColorStops(colorStops: ColorStop[], maxSize: number): ColorStop[] {
const newColorStops: ColorStop[] = [];
const len = colorStops.length;
// coord will always < 0 in prevOutOfRangeColorStop.
let prevOutOfRangeColorStop: ColorStop;
let prevInRangeColorStop: ColorStop;
function lerpStop(stop0: ColorStop, stop1: ColorStop, clippedCoord: number) {
const coord0 = stop0.coord;
const p = (clippedCoord - coord0) / (stop1.coord - coord0);
const color = lerp(p, [stop0.color, stop1.color]) as string;
return { coord: clippedCoord, color } as ColorStop;
}
for (let i = 0; i < len; i++) {
const stop = colorStops[i];
const coord = stop.coord;
if (coord < 0) {
prevOutOfRangeColorStop = stop;
}
else if (coord > maxSize) {
if (prevInRangeColorStop) {
newColorStops.push(lerpStop(prevInRangeColorStop, stop, maxSize));
}
else if (prevOutOfRangeColorStop) { // If there are two stops and coord range is between these two stops
newColorStops.push(
lerpStop(prevOutOfRangeColorStop, stop, 0),
lerpStop(prevOutOfRangeColorStop, stop, maxSize)
);
}
// All following stop will be out of range. So just ignore them.
break;
}
else {
if (prevOutOfRangeColorStop) {
newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop, 0));
// Reset
prevOutOfRangeColorStop = null;
}
newColorStops.push(stop);
prevInRangeColorStop = stop;
}
}
return newColorStops;
}
function getVisualGradient(
data: SeriesData,
coordSys: Cartesian2D | Polar,
api: ExtensionAPI
) {
const visualMetaList = data.getVisual('visualMeta');
if (!visualMetaList || !visualMetaList.length || !data.count()) {
// When data.count() is 0, gradient range can not be calculated.
return;
}
if (coordSys.type !== 'cartesian2d') {
if (__DEV__) {
console.warn('Visual map on line style is only supported on cartesian2d.');
}
return;
}
let coordDim: 'x' | 'y';
let visualMeta;
for (let i = visualMetaList.length - 1; i >= 0; i--) {
const dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
coordDim = (dimInfo && dimInfo.coordDim) as 'x' | 'y';
// Can only be x or y
if (coordDim === 'x' || coordDim === 'y') {
visualMeta = visualMetaList[i];
break;
}
}
if (!visualMeta) {
if (__DEV__) {
console.warn('Visual map on line style only support x or y dimension.');
}
return;
}
// If the area to be rendered is bigger than area defined by LinearGradient,
// the canvas spec prescribes that the color of the first stop and the last
// stop should be used. But if two stops are added at offset 0, in effect
// browsers use the color of the second stop to render area outside
// LinearGradient. So we can only infinitesimally extend area defined in
// LinearGradient to render `outerColors`.
const axis = coordSys.getAxis(coordDim);
// dataToCoord mapping may not be linear, but must be monotonic.
const colorStops: ColorStop[] = zrUtil.map(visualMeta.stops, function (stop) {
// offset will be calculated later.
return {
coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
color: stop.color
} as ColorStop;
});
const stopLen = colorStops.length;
const outerColors = visualMeta.outerColors.slice();
if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
colorStops.reverse();
outerColors.reverse();
}
const colorStopsInRange = clipColorStops(
colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight()
);
const inRangeStopLen = colorStopsInRange.length;
if (!inRangeStopLen && stopLen) {
// All stops are out of range. All will be the same color.
return colorStops[0].coord < 0
? (outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color)
: (outerColors[0] ? outerColors[0] : colorStops[0].color);
}
const tinyExtent = 10; // Arbitrary value: 10px
const minCoord = colorStopsInRange[0].coord - tinyExtent;
const maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
const coordSpan = maxCoord - minCoord;
if (coordSpan < 1e-3) {
return 'transparent';
}
zrUtil.each(colorStopsInRange, function (stop) {
stop.offset = (stop.coord - minCoord) / coordSpan;
});
colorStopsInRange.push({
// NOTE: inRangeStopLen may still be 0 if stoplen is zero.
offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
color: outerColors[1] || 'transparent'
});
colorStopsInRange.unshift({ // notice newColorStops.length have been changed.
offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
color: outerColors[0] || 'transparent'
});
const gradient = new graphic.LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
gradient[coordDim] = minCoord;
gradient[coordDim + '2' as 'x2' | 'y2'] = maxCoord;
return gradient;
}
function getIsIgnoreFunc(
seriesModel: LineSeriesModel,
data: SeriesData,
coordSys: Cartesian2D
) {
const showAllSymbol = seriesModel.get('showAllSymbol');
const isAuto = showAllSymbol === 'auto';
if (showAllSymbol && !isAuto) {
return;
}
const categoryAxis = coordSys.getAxesByScale('ordinal')[0];
if (!categoryAxis) {
return;
}
// Note that category label interval strategy might bring some weird effect
// in some scenario: users may wonder why some of the symbols are not
// displayed. So we show all symbols as possible as we can.
if (isAuto
// Simplify the logic, do not determine label overlap here.
&& canShowAllSymbolForCategory(categoryAxis, data)
) {
return;
}
// Otherwise follow the label interval strategy on category axis.
const categoryDataDim = data.mapDimension(categoryAxis.dim);
const labelMap: Dictionary<1> = {};
zrUtil.each(categoryAxis.getViewLabels(), function (labelItem) {
const ordinalNumber = (categoryAxis.scale as OrdinalScale)
.getRawOrdinalNumber(labelItem.tickValue);
labelMap[ordinalNumber] = 1;
});
return function (dataIndex: number) {
return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
};
}
function canShowAllSymbolForCategory(
categoryAxis: Axis2D,
data: SeriesData
) {
// In most cases, line is monotonous on category axis, and the label size
// is close with each other. So we check the symbol size and some of the
// label size alone with the category axis to estimate whether all symbol
// can be shown without overlap.
const axisExtent = categoryAxis.getExtent();
let availSize = Math.abs(axisExtent[1] - axisExtent[0]) / (categoryAxis.scale as OrdinalScale).count();
isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
// Sampling some points, max 5.
const dataLen = data.count();
const step = Math.max(1, Math.round(dataLen / 5));
for (let dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
if (SymbolClz.getSymbolSize(
data, dataIndex
// Only for cartesian, where `isHorizontal` exists.
)[categoryAxis.isHorizontal() ? 1 : 0]
// Empirical number
* 1.5 > availSize
) {
return false;
}
}
return true;
}
function isPointNull(x: number, y: number) {
return isNaN(x) || isNaN(y);
}
function getLastIndexNotNull(points: ArrayLike<number>) {
let len = points.length / 2;
for (; len > 0; len--) {
if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
break;
}
}
return len - 1;
}
function getPointAtIndex(points: ArrayLike<number>, idx: number) {
return [points[idx * 2], points[idx * 2 + 1]];
}
function getIndexRange(points: ArrayLike<number>, xOrY: number, dim: 'x' | 'y') {
const len = points.length / 2;
const dimIdx = dim === 'x' ? 0 : 1;
let a;
let b;
let prevIndex = 0;
let nextIndex = -1;
for (let i = 0; i < len; i++) {
b = points[i * 2 + dimIdx];
if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
continue;
}
if (i === 0) {
a = b;
continue;
}
if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
nextIndex = i;
break;
}
prevIndex = i;
a = b;
}
return {
range: [prevIndex, nextIndex],
t: (xOrY - a) / (b - a)
};
}
function anyStateShowEndLabel(
seriesModel: LineSeriesModel
) {
if (seriesModel.get(['endLabel', 'show'])) {
return true;
}
for (let i = 0; i < SPECIAL_STATES.length; i++) {
if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
return true;
}
}
return false;
}
interface EndLabelAnimationRecord {
lastFrameIndex: number
originalX?: number
originalY?: number
}
function createLineClipPath(
lineView: LineView,
coordSys: Cartesian2D | Polar,
hasAnimation: boolean,
seriesModel: LineSeriesModel
) {
if (isCoordinateSystemType<Cartesian2D>(coordSys, 'cartesian2d')) {
const endLabelModel = seriesModel.getModel('endLabel');
const valueAnimation = endLabelModel.get('valueAnimation');
const data = seriesModel.getData();
const labelAnimationRecord: EndLabelAnimationRecord = { lastFrameIndex: 0 };
const during = anyStateShowEndLabel(seriesModel)
? (percent: number, clipRect: graphic.Rect) => {
lineView._endLabelOnDuring(
percent,
clipRect,
data,
labelAnimationRecord,
valueAnimation,
endLabelModel,
coordSys
);
}
: null;
const isHorizontal = coordSys.getBaseAxis().isHorizontal();
const clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, () => {
const endLabel = lineView._endLabel;
if (endLabel && hasAnimation) {
if (labelAnimationRecord.originalX != null) {
endLabel.attr({
x: labelAnimationRecord.originalX,
y: labelAnimationRecord.originalY
});
}
}
}, during);
// Expand clip shape to avoid clipping when line value exceeds axis
if (!seriesModel.get('clip', true)) {
const rectShape = clipPath.shape;
const expandSize = Math.max(rectShape.width, rectShape.height);
if (isHorizontal) {
rectShape.y -= expandSize;
rectShape.height += expandSize * 2;
}
else {
rectShape.x -= expandSize;
rectShape.width += expandSize * 2;
}
}
// Set to the final frame. To make sure label layout is right.
if (during) {
during(1, clipPath);
}
return clipPath;
}
else {
if (__DEV__) {
if (seriesModel.get(['endLabel', 'show'])) {
console.warn('endLabel is not supported for lines in polar systems.');
}
}
return createPolarClipPath(coordSys, hasAnimation, seriesModel);
}
}
function getEndLabelStateSpecified(endLabelModel: Model, coordSys: Cartesian2D) {
const baseAxis = coordSys.getBaseAxis();
const isHorizontal = baseAxis.isHorizontal();
const isBaseInversed = baseAxis.inverse;
const align = isHorizontal
? (isBaseInversed ? 'right' : 'left')
: 'center';
const verticalAlign = isHorizontal
? 'middle'
: (isBaseInversed ? 'top' : 'bottom');
return {
normal: {
align: endLabelModel.get('align') || align,
verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
}
};
}
class LineView extends ChartView {
static readonly type = 'line';
_symbolDraw: SymbolDraw;
_lineGroup: graphic.Group;
_coordSys: Cartesian2D | Polar;
_endLabel: graphic.Text;
_polyline: ECPolyline;
_polygon: ECPolygon;
_stackedOnPoints: ArrayLike<number>;
_points: ArrayLike<number>;
_step: LineSeriesOption['step'];
_valueOrigin: LineSeriesOption['areaStyle']['origin'];
_clipShapeForSymbol: CoordinateSystemClipArea;
_data: SeriesData;
init() {
const lineGroup = new graphic.Group();
const symbolDraw = new SymbolDraw();
this.group.add(symbolDraw.group);
this._symbolDraw = symbolDraw;
this._lineGroup = lineGroup;
this._changePolyState = zrUtil.bind(this._changePolyState, this);
}
render(seriesModel: LineSeriesModel, ecModel: GlobalModel, api: ExtensionAPI) {
const coordSys = seriesModel.coordinateSystem;
const group = this.group;
const data = seriesModel.getData();
const lineStyleModel = seriesModel.getModel('lineStyle');
const areaStyleModel = seriesModel.getModel('areaStyle');
let points = data.getLayout('points') as number[] || [];
const isCoordSysPolar = coordSys.type === 'polar';
const prevCoordSys = this._coordSys;
const symbolDraw = this._symbolDraw;
let polyline = this._polyline;
let polygon = this._polygon;
const lineGroup = this._lineGroup;
const hasAnimation = !ecModel.ssr && seriesModel.get('animation');
const isAreaChart = !areaStyleModel.isEmpty();
const valueOrigin = areaStyleModel.get('origin');
const dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
let stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
const showSymbol = seriesModel.get('showSymbol');
const connectNulls = seriesModel.get('connectNulls');
const isIgnoreFunc = showSymbol && !isCoordSysPolar
&& getIsIgnoreFunc(seriesModel, data, coordSys as Cartesian2D);
// Remove temporary symbols
const oldData = this._data;
oldData && oldData.eachItemGraphicEl(function (el: SymbolExtended, idx) {
if (el.__temp) {
group.remove(el);
oldData.setItemGraphicEl(idx, null);
}
});
// Remove previous created symbols if showSymbol changed to false
if (!showSymbol) {
symbolDraw.remove();
}
group.add(lineGroup);
// FIXME step not support polar
const step = !isCoordSysPolar ? seriesModel.get('step') : false;
let clipShapeForSymbol: PolarArea | Cartesian2DArea;
if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
clipShapeForSymbol = coordSys.getArea();
// Avoid float number rounding error for symbol on the edge of axis extent.
// See #7913 and `test/dataZoom-clip.html`.
if ((clipShapeForSymbol as Cartesian2DArea).width != null) {
(clipShapeForSymbol as Cartesian2DArea).x -= 0.1;
(clipShapeForSymbol as Cartesian2DArea).y -= 0.1;
(clipShapeForSymbol as Cartesian2DArea).width += 0.2;
(clipShapeForSymbol as Cartesian2DArea).height += 0.2;
}
else if ((clipShapeForSymbol as PolarArea).r0) {
(clipShapeForSymbol as PolarArea).r0 -= 0.5;
(clipShapeForSymbol as PolarArea).r += 0.5;
}
}
this._clipShapeForSymbol = clipShapeForSymbol;
const visualColor = getVisualGradient(data, coordSys, api)
|| data.getVisual('style')[data.getVisual('drawType')];
// Initialization animation or coordinate system changed
if (
!(polyline && prevCoordSys.type === coordSys.type && step === this._step)
) {
showSymbol && symbolDraw.updateData(data, {
isIgnore: isIgnoreFunc,
clipShape: clipShapeForSymbol,
disableAnimation: true,
getSymbolPoint(idx) {
return [points[idx * 2], points[idx * 2 + 1]];
}
});
hasAnimation && this._initSymbolLabelAnimation(
data,
coordSys,
clipShapeForSymbol
);
if (step) {
if (stackedOnPoints) {
stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
}
// TODO If stacked series is not step
points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
}
polyline = this._newPolyline(points);
if (isAreaChart) {
polygon = this._newPolygon(
points, stackedOnPoints
);
}// If areaStyle is removed
else if (polygon) {
lineGroup.remove(polygon);
polygon = this._polygon = null;
}
// NOTE: Must update _endLabel before setClipPath.
if (!isCoordSysPolar) {
this._initOrUpdateEndLabel(seriesModel, coordSys as Cartesian2D, convertToColorString(visualColor));
}
lineGroup.setClipPath(
createLineClipPath(this, coordSys, true, seriesModel)
);
}
else {
if (isAreaChart && !polygon) {
// If areaStyle is added
polygon = this._newPolygon(
points, stackedOnPoints
);
}
else if (polygon && !isAreaChart) {
// If areaStyle is removed
lineGroup.remove(polygon);
polygon = this._polygon = null;
}
// NOTE: Must update _endLabel before setClipPath.
if (!isCoordSysPolar) {
this._initOrUpdateEndLabel(seriesModel, coordSys as Cartesian2D, convertToColorString(visualColor));
}
// Update clipPath
const oldClipPath = lineGroup.getClipPath();
if (oldClipPath) {
const newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
graphic.initProps(oldClipPath, {
shape: newClipPath.shape
}, seriesModel);
}
else {
lineGroup.setClipPath(
createLineClipPath(this, coordSys, true, seriesModel)
);
}
// Always update, or it is wrong in the case turning on legend
// because points are not changed.
showSymbol && symbolDraw.updateData(data, {
isIgnore: isIgnoreFunc,
clipShape: clipShapeForSymbol,
disableAnimation: true,
getSymbolPoint(idx) {
return [points[idx * 2], points[idx * 2 + 1]];
}
});
// In the case data zoom triggered refreshing frequently
// Data may not change if line has a category axis. So it should animate nothing.
if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
|| !isPointsSame(this._points, points)
) {
if (hasAnimation) {
this._doUpdateAnimation(
data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls
);
}
else {
// Not do it in update with animation
if (step) {
if (stackedOnPoints) {
stackedOnPoints = turnPointsIntoStep(stackedOnPoints, points, coordSys, step, connectNulls);
}
// TODO If stacked series is not step
points = turnPointsIntoStep(points, null, coordSys, step, connectNulls);
}
polyline.setShape({
points: points
});
polygon && polygon.setShape({
points: points,
stackedOnPoints: stackedOnPoints
});
}
}
}
const emphasisModel = seriesModel.getModel('emphasis');
const focus = emphasisModel.get('focus');
const blurScope = emphasisModel.get('blurScope');
const emphasisDisabled = emphasisModel.get('disabled');
polyline.useStyle(zrUtil.defaults(
// Use color in lineStyle first
lineStyleModel.getLineStyle(),
{
fill: 'none',
stroke: visualColor,
lineJoin: 'bevel' as CanvasLineJoin
}
));
setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
const emphasisLineStyle = polyline.getState('emphasis').style;
emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
}
// Needs seriesIndex for focus
getECData(polyline).seriesIndex = seriesModel.seriesIndex;
toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
const smooth = getSmooth(seriesModel.get('smooth'));
const smoothMonotone = seriesModel.get('smoothMonotone');
polyline.setShape({
smooth,
smoothMonotone,
connectNulls
});
if (polygon) {
const stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
let stackedOnSmooth = 0;
polygon.useStyle(zrUtil.defaults(
areaStyleModel.getAreaStyle(),
{
fill: visualColor,
opacity: 0.7,
lineJoin: 'bevel' as CanvasLineJoin,
decal: data.getVisual('style').decal
}
));
if (stackedOnSeries) {
stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
}
polygon.setShape({
smooth,
stackedOnSmooth,
smoothMonotone,
connectNulls
});
setStatesStylesFromModel(polygon, seriesModel, 'areaStyle');
// Needs seriesIndex for focus
getECData(polygon).seriesIndex = seriesModel.seriesIndex;
toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
}
const changePolyState = this._changePolyState;
data.eachItemGraphicEl(function (el) {
// Switch polyline / polygon state if element changed its state.
el && ((el as ECElement).onHoverStateChange = changePolyState);
});
(this._polyline as ECElement).onHoverStateChange = changePolyState;
this._data = data;
// Save the coordinate system for transition animation when data changed
this._coordSys = coordSys;
this._stackedOnPoints = stackedOnPoints;
this._points = points;
this._step = step;
this._valueOrigin = valueOrigin;
if (seriesModel.get('triggerLineEvent')) {
this.packEventData(seriesModel, polyline);
polygon && this.packEventData(seriesModel, polygon);
}
}
private packEventData(seriesModel: LineSeriesModel, el: Element) {
getECData(el).eventData = {
componentType: 'series',
componentSubType: 'line',
componentIndex: seriesModel.componentIndex,
seriesIndex: seriesModel.seriesIndex,
seriesName: seriesModel.name,
seriesType: 'line'
};
}
highlight(
seriesModel: LineSeriesModel,
ecModel: GlobalModel,
api: ExtensionAPI,
payload: Payload
) {
const data = seriesModel.getData();
const dataIndex = modelUtil.queryDataIndex(data, payload);
this._changePolyState('emphasis');
if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
const points = data.getLayout('points');
let symbol = data.getItemGraphicEl(dataIndex) as SymbolClz;
if (!symbol) {
// Create a temporary symbol if it is not exists
const x = points[dataIndex * 2];
const y = points[dataIndex * 2 + 1];
if (isNaN(x) || isNaN(y)) {
// Null data
return;
}
// fix #11360: shouldn't draw symbol outside clipShapeForSymbol
if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
return;
}
const zlevel = seriesModel.get('zlevel') || 0;
const z = seriesModel.get('z') || 0;
symbol = new SymbolClz(data, dataIndex);
symbol.x = x;
symbol.y = y;
symbol.setZ(zlevel, z);
// ensure label text of the temporary symbol is in front of line and area polygon
const symbolLabel = symbol.getSymbolPath().getTextContent();
if (symbolLabel) {
symbolLabel.zlevel = zlevel;
symbolLabel.z = z;
symbolLabel.z2 = this._polyline.z2 + 1;
}
(symbol as SymbolExtended).__temp = true;
data.setItemGraphicEl(dataIndex, symbol);
// Stop scale animation
symbol.stopSymbolAnimation(true);
this.group.add(symbol);
}
symbol.highlight();
}
else {
// Highlight whole series
ChartView.prototype.highlight.call(
this, seriesModel, ecModel, api, payload
);
}
}
downplay(
seriesModel: LineSeriesModel,