-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathecharts.ts
3083 lines (2648 loc) · 108 KB
/
echarts.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.
*/
import * as zrender from 'zrender/src/zrender';
import {
assert,
each,
isFunction,
isObject,
indexOf,
bind,
clone,
setAsPrimitive,
extend,
HashMap,
createHashMap,
map,
defaults,
isDom,
isArray,
noop,
isString,
retrieve2
} from 'zrender/src/core/util';
import env from 'zrender/src/core/env';
import timsort from 'zrender/src/core/timsort';
import Eventful, { EventCallbackSingleParam } from 'zrender/src/core/Eventful';
import Element, { ElementEvent } from 'zrender/src/Element';
import GlobalModel, {QueryConditionKindA, GlobalModelSetOptionOpts} from '../model/Global';
import ExtensionAPI from './ExtensionAPI';
import CoordinateSystemManager from './CoordinateSystem';
import OptionManager from '../model/OptionManager';
import backwardCompat from '../preprocessor/backwardCompat';
import dataStack from '../processor/dataStack';
import ComponentModel from '../model/Component';
import SeriesModel from '../model/Series';
import ComponentView, {ComponentViewConstructor} from '../view/Component';
import ChartView, {ChartViewConstructor} from '../view/Chart';
import * as graphic from '../util/graphic';
import {getECData} from '../util/innerStore';
import {
isHighDownDispatcher,
HOVER_STATE_EMPHASIS,
HOVER_STATE_BLUR,
blurSeriesFromHighlightPayload,
toggleSelectionFromPayload,
updateSeriesElementSelection,
getAllSelectedIndices,
isSelectChangePayload,
isHighDownPayload,
HIGHLIGHT_ACTION_TYPE,
DOWNPLAY_ACTION_TYPE,
SELECT_ACTION_TYPE,
UNSELECT_ACTION_TYPE,
TOGGLE_SELECT_ACTION_TYPE,
savePathStates,
enterEmphasis,
leaveEmphasis,
leaveBlur,
enterSelect,
leaveSelect,
enterBlur,
allLeaveBlur,
findComponentHighDownDispatchers,
blurComponent,
handleGlobalMouseOverForHighDown,
handleGlobalMouseOutForHighDown
} from '../util/states';
import * as modelUtil from '../util/model';
import {throttle} from '../util/throttle';
import {seriesStyleTask, dataStyleTask, dataColorPaletteTask} from '../visual/style';
import loadingDefault from '../loading/default';
import Scheduler from './Scheduler';
import lightTheme from '../theme/light';
import darkTheme from '../theme/dark';
import {CoordinateSystemMaster, CoordinateSystemCreator, CoordinateSystemHostModel} from '../coord/CoordinateSystem';
import { parseClassType } from '../util/clazz';
import {ECEventProcessor} from '../util/ECEventProcessor';
import {
Payload, ECElement, RendererType, ECActionEvent,
ActionHandler, ActionInfo, OptionPreprocessor, PostUpdater,
LoadingEffect, LoadingEffectCreator, StageHandlerInternal,
StageHandlerOverallReset, StageHandler,
ViewRootGroup, DimensionDefinitionLoose, ECEventData, ThemeOption,
ECBasicOption,
ECUnitOption,
ZRColor,
ComponentMainType,
ComponentSubType,
ColorString,
SelectChangedPayload,
ScaleDataValue,
ZRElementEventName,
ECElementEvent,
AnimationOption
} from '../util/types';
import Displayable from 'zrender/src/graphic/Displayable';
import { seriesSymbolTask, dataSymbolTask } from '../visual/symbol';
import { getVisualFromData, getItemVisualFromData } from '../visual/helper';
import { deprecateLog, deprecateReplaceLog, error, warn } from '../util/log';
import { handleLegacySelectEvents } from '../legacy/dataSelectAction';
import { registerExternalTransform } from '../data/helper/transform';
import { createLocaleObject, SYSTEM_LANG, LocaleOption } from './locale';
import type {EChartsOption} from '../export/option';
import { findEventDispatcher } from '../util/event';
import decal from '../visual/decal';
import CanvasPainter from 'zrender/src/canvas/Painter';
import SVGPainter from 'zrender/src/svg/Painter';
import lifecycle, {
LifecycleEvents,
UpdateLifecycleTransitionItem,
UpdateLifecycleParams,
UpdateLifecycleTransitionOpt
} from './lifecycle';
import { platformApi, setPlatformAPI } from 'zrender/src/core/platform';
import { getImpl } from './impl';
import type geoSourceManager from '../coord/geo/geoSourceManager';
declare let global: any;
type ModelFinder = modelUtil.ModelFinder;
export const version = '5.5.1';
export const dependencies = {
zrender: '5.6.0'
};
const TEST_FRAME_REMAIN_TIME = 1;
const PRIORITY_PROCESSOR_SERIES_FILTER = 800;
// Some data processors depends on the stack result dimension (to calculate data extent).
// So data stack stage should be in front of data processing stage.
const PRIORITY_PROCESSOR_DATASTACK = 900;
// "Data filter" will block the stream, so it should be
// put at the beginning of data processing.
const PRIORITY_PROCESSOR_FILTER = 1000;
const PRIORITY_PROCESSOR_DEFAULT = 2000;
const PRIORITY_PROCESSOR_STATISTIC = 5000;
const PRIORITY_VISUAL_LAYOUT = 1000;
const PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
const PRIORITY_VISUAL_GLOBAL = 2000;
const PRIORITY_VISUAL_CHART = 3000;
const PRIORITY_VISUAL_COMPONENT = 4000;
// Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
// overwrite the viusal result of component (like `visualMap`)
// using data item specific setting (like itemStyle.xxx on data item)
const PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500;
// Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
// visual result like `symbolSize`.
const PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
const PRIORITY_VISUAL_BRUSH = 5000;
const PRIORITY_VISUAL_ARIA = 6000;
const PRIORITY_VISUAL_DECAL = 7000;
export const PRIORITY = {
PROCESSOR: {
FILTER: PRIORITY_PROCESSOR_FILTER,
SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
STATISTIC: PRIORITY_PROCESSOR_STATISTIC
},
VISUAL: {
LAYOUT: PRIORITY_VISUAL_LAYOUT,
PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
GLOBAL: PRIORITY_VISUAL_GLOBAL,
CHART: PRIORITY_VISUAL_CHART,
POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
COMPONENT: PRIORITY_VISUAL_COMPONENT,
BRUSH: PRIORITY_VISUAL_BRUSH,
CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
ARIA: PRIORITY_VISUAL_ARIA,
DECAL: PRIORITY_VISUAL_DECAL
}
};
// Main process have three entries: `setOption`, `dispatchAction` and `resize`,
// where they must not be invoked nestedly, except the only case: invoke
// dispatchAction with updateMethod "none" in main process.
// This flag is used to carry out this rule.
// All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
const IN_MAIN_PROCESS_KEY = '__flagInMainProcess' as const;
const PENDING_UPDATE = '__pendingUpdate' as const;
const STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus' as const;
const ACTION_REG = /^[a-zA-Z0-9_]+$/;
const CONNECT_STATUS_KEY = '__connectUpdateStatus' as const;
const CONNECT_STATUS_PENDING = 0 as const;
const CONNECT_STATUS_UPDATING = 1 as const;
const CONNECT_STATUS_UPDATED = 2 as const;
type ConnectStatus =
typeof CONNECT_STATUS_PENDING
| typeof CONNECT_STATUS_UPDATING
| typeof CONNECT_STATUS_UPDATED;
export type SetOptionTransitionOpt = UpdateLifecycleTransitionOpt;
export type SetOptionTransitionOptItem = UpdateLifecycleTransitionItem;
export interface SetOptionOpts {
notMerge?: boolean;
lazyUpdate?: boolean;
silent?: boolean;
// Rule: only `id` mapped will be merged,
// other components of the certain `mainType` will be removed.
replaceMerge?: GlobalModelSetOptionOpts['replaceMerge'];
transition?: SetOptionTransitionOpt
};
export interface ResizeOpts {
width?: number | 'auto', // Can be 'auto' (the same as null/undefined)
height?: number | 'auto', // Can be 'auto' (the same as null/undefined)
animation?: AnimationOption
silent?: boolean // by default false.
};
interface PostIniter {
(chart: EChartsType): void
}
type EventMethodName = 'on' | 'off';
function createRegisterEventWithLowercaseECharts(method: EventMethodName) {
return function (this: ECharts, ...args: any): ECharts {
if (this.isDisposed()) {
disposedWarning(this.id);
return;
}
return toLowercaseNameAndCallEventful<ECharts>(this, method, args);
};
}
function createRegisterEventWithLowercaseMessageCenter(method: EventMethodName) {
return function (this: MessageCenter, ...args: any): MessageCenter {
return toLowercaseNameAndCallEventful<MessageCenter>(this, method, args);
};
}
function toLowercaseNameAndCallEventful<T>(host: T, method: EventMethodName, args: any): T {
// `args[0]` is event name. Event name is all lowercase.
args[0] = args[0] && args[0].toLowerCase();
return Eventful.prototype[method].apply(host, args) as any;
}
class MessageCenter extends Eventful {}
const messageCenterProto = MessageCenter.prototype;
messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off');
// ---------------------------------------
// Internal method names for class ECharts
// ---------------------------------------
let prepare: (ecIns: ECharts) => void;
let prepareView: (ecIns: ECharts, isComponent: boolean) => void;
let updateDirectly: (
ecIns: ECharts, method: string, payload: Payload, mainType: ComponentMainType, subType?: ComponentSubType
) => void;
type UpdateMethod = (this: ECharts, payload?: Payload, renderParams?: UpdateLifecycleParams) => void;
let updateMethods: {
prepareAndUpdate: UpdateMethod,
update: UpdateMethod,
updateTransform: UpdateMethod,
updateView: UpdateMethod,
updateVisual: UpdateMethod,
updateLayout: UpdateMethod
};
let doConvertPixel: (
ecIns: ECharts,
methodName: string,
finder: ModelFinder,
value: (number | number[]) | (ScaleDataValue | ScaleDataValue[])
) => (number | number[]);
let updateStreamModes: (ecIns: ECharts, ecModel: GlobalModel) => void;
let doDispatchAction: (this: ECharts, payload: Payload, silent: boolean) => void;
let flushPendingActions: (this: ECharts, silent: boolean) => void;
let triggerUpdatedEvent: (this: ECharts, silent: boolean) => void;
let bindRenderedEvent: (zr: zrender.ZRenderType, ecIns: ECharts) => void;
let bindMouseEvent: (zr: zrender.ZRenderType, ecIns: ECharts) => void;
let render: (
ecIns: ECharts, ecModel: GlobalModel, api: ExtensionAPI, payload: Payload, updateParams: UpdateLifecycleParams
) => void;
let renderComponents: (
ecIns: ECharts, ecModel: GlobalModel, api: ExtensionAPI, payload: Payload,
updateParams: UpdateLifecycleParams, dirtyList?: ComponentView[]
) => void;
let renderSeries: (
ecIns: ECharts, ecModel: GlobalModel, api: ExtensionAPI, payload: Payload | 'remain',
updateParams: UpdateLifecycleParams,
dirtyMap?: {[uid: string]: any}
) => void;
let createExtensionAPI: (ecIns: ECharts) => ExtensionAPI;
let enableConnect: (ecIns: ECharts) => void;
let markStatusToUpdate: (ecIns: ECharts) => void;
let applyChangedStates: (ecIns: ECharts) => void;
type RenderedEventParam = { elapsedTime: number };
type ECEventDefinition = {
[key in ZRElementEventName]: EventCallbackSingleParam<ECElementEvent>
} & {
rendered: EventCallbackSingleParam<RenderedEventParam>
finished: () => void | boolean
} & {
// TODO: Use ECActionEvent
[key: string]: (...args: unknown[]) => void | boolean
};
export type EChartsInitOpts = {
locale?: string | LocaleOption,
renderer?: RendererType,
devicePixelRatio?: number,
useDirtyRect?: boolean,
useCoarsePointer?: boolean,
pointerSize?: number,
ssr?: boolean,
width?: number | string,
height?: number | string
};
class ECharts extends Eventful<ECEventDefinition> {
/**
* @readonly
*/
id: string;
/**
* Group id
* @readonly
*/
group: string;
private _ssr: boolean;
private _zr: zrender.ZRenderType;
private _dom: HTMLElement;
private _model: GlobalModel;
private _throttledZrFlush: zrender.ZRenderType extends {flush: infer R} ? R : never;
private _theme: ThemeOption;
private _locale: LocaleOption;
private _chartsViews: ChartView[] = [];
private _chartsMap: {[viewId: string]: ChartView} = {};
private _componentsViews: ComponentView[] = [];
private _componentsMap: {[viewId: string]: ComponentView} = {};
private _coordSysMgr: CoordinateSystemManager;
private _api: ExtensionAPI;
private _scheduler: Scheduler;
private _messageCenter: MessageCenter;
// Can't dispatch action during rendering procedure
private _pendingActions: Payload[] = [];
// We use never here so ECEventProcessor will not been exposed.
// which may include many unexpected types won't be exposed in the types to developers.
protected _$eventProcessor: never;
private _disposed: boolean;
private _loadingFX: LoadingEffect;
private [PENDING_UPDATE]: {
silent: boolean
updateParams: UpdateLifecycleParams
};
private [IN_MAIN_PROCESS_KEY]: boolean;
private [CONNECT_STATUS_KEY]: ConnectStatus;
private [STATUS_NEEDS_UPDATE_KEY]: boolean;
constructor(
dom: HTMLElement,
// Theme name or themeOption.
theme?: string | ThemeOption,
opts?: EChartsInitOpts
) {
super(new ECEventProcessor());
opts = opts || {};
// Get theme by name
if (isString(theme)) {
theme = themeStorage[theme] as object;
}
this._dom = dom;
let defaultRenderer = 'canvas';
let defaultCoarsePointer: 'auto' | boolean = 'auto';
let defaultUseDirtyRect = false;
if (__DEV__) {
const root = (
/* eslint-disable-next-line */
env.hasGlobalWindow ? window : global
) as any;
if (root) {
defaultRenderer = retrieve2(root.__ECHARTS__DEFAULT__RENDERER__, defaultRenderer);
defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
defaultUseDirtyRect = retrieve2(root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__, defaultUseDirtyRect);
}
}
if (opts.ssr) {
zrender.registerSSRDataGetter(el => {
const ecData = getECData(el);
const dataIndex = ecData.dataIndex;
if (dataIndex == null) {
return;
}
const hashMap = createHashMap();
hashMap.set('series_index', ecData.seriesIndex);
hashMap.set('data_index', dataIndex);
ecData.ssrType && hashMap.set('ssr_type', ecData.ssrType);
return hashMap;
});
}
const zr = this._zr = zrender.init(dom, {
renderer: opts.renderer || defaultRenderer,
devicePixelRatio: opts.devicePixelRatio,
width: opts.width,
height: opts.height,
ssr: opts.ssr,
useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
pointerSize: opts.pointerSize
});
this._ssr = opts.ssr;
// Expect 60 fps.
this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
theme = clone(theme);
theme && backwardCompat(theme as ECUnitOption, true);
this._theme = theme;
this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
this._coordSysMgr = new CoordinateSystemManager();
const api = this._api = createExtensionAPI(this);
// Sort on demand
function prioritySortFunc(a: StageHandlerInternal, b: StageHandlerInternal): number {
return a.__prio - b.__prio;
}
timsort(visualFuncs, prioritySortFunc);
timsort(dataProcessorFuncs, prioritySortFunc);
this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
this._messageCenter = new MessageCenter();
// Init mouse events
this._initEvents();
// In case some people write `window.onresize = chart.resize`
this.resize = bind(this.resize, this);
zr.animation.on('frame', this._onframe, this);
bindRenderedEvent(zr, this);
bindMouseEvent(zr, this);
// ECharts instance can be used as value.
setAsPrimitive(this);
}
private _onframe(): void {
if (this._disposed) {
return;
}
applyChangedStates(this);
const scheduler = this._scheduler;
// Lazy update
if (this[PENDING_UPDATE]) {
const silent = (this[PENDING_UPDATE] as any).silent;
this[IN_MAIN_PROCESS_KEY] = true;
try {
prepare(this);
updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
}
catch (e) {
this[IN_MAIN_PROCESS_KEY] = false;
this[PENDING_UPDATE] = null;
throw e;
}
// At present, in each frame, zrender performs:
// (1) animation step forward.
// (2) trigger('frame') (where this `_onframe` is called)
// (3) zrender flush (render).
// If we do nothing here, since we use `setToFinal: true`, the step (3) above
// will render the final state of the elements before the real animation started.
this._zr.flush();
this[IN_MAIN_PROCESS_KEY] = false;
this[PENDING_UPDATE] = null;
flushPendingActions.call(this, silent);
triggerUpdatedEvent.call(this, silent);
}
// Avoid do both lazy update and progress in one frame.
else if (scheduler.unfinished) {
// Stream progress.
let remainTime = TEST_FRAME_REMAIN_TIME;
const ecModel = this._model;
const api = this._api;
scheduler.unfinished = false;
do {
const startTime = +new Date();
scheduler.performSeriesTasks(ecModel);
// Currently dataProcessorFuncs do not check threshold.
scheduler.performDataProcessorTasks(ecModel);
updateStreamModes(this, ecModel);
// Do not update coordinate system here. Because that coord system update in
// each frame is not a good user experience. So we follow the rule that
// the extent of the coordinate system is determined in the first frame (the
// frame is executed immediately after task reset.
// this._coordSysMgr.update(ecModel, api);
// console.log('--- ec frame visual ---', remainTime);
scheduler.performVisualTasks(ecModel);
renderSeries(this, this._model, api, 'remain', {});
remainTime -= (+new Date() - startTime);
}
while (remainTime > 0 && scheduler.unfinished);
// Call flush explicitly for trigger finished event.
if (!scheduler.unfinished) {
this._zr.flush();
}
// Else, zr flushing be ensue within the same frame,
// because zr flushing is after onframe event.
}
}
getDom(): HTMLElement {
return this._dom;
}
getId(): string {
return this.id;
}
getZr(): zrender.ZRenderType {
return this._zr;
}
isSSR(): boolean {
return this._ssr;
}
/**
* Usage:
* chart.setOption(option, notMerge, lazyUpdate);
* chart.setOption(option, {
* notMerge: ...,
* lazyUpdate: ...,
* silent: ...
* });
*
* @param opts opts or notMerge.
* @param opts.notMerge Default `false`.
* @param opts.lazyUpdate Default `false`. Useful when setOption frequently.
* @param opts.silent Default `false`.
* @param opts.replaceMerge Default undefined.
*/
// Expose to user full option.
setOption<Opt extends ECBasicOption>(option: Opt, notMerge?: boolean, lazyUpdate?: boolean): void;
setOption<Opt extends ECBasicOption>(option: Opt, opts?: SetOptionOpts): void;
/* eslint-disable-next-line */
setOption<Opt extends ECBasicOption>(option: Opt, notMerge?: boolean | SetOptionOpts, lazyUpdate?: boolean): void {
if (this[IN_MAIN_PROCESS_KEY]) {
if (__DEV__) {
error('`setOption` should not be called during main process.');
}
return;
}
if (this._disposed) {
disposedWarning(this.id);
return;
}
let silent;
let replaceMerge;
let transitionOpt: SetOptionTransitionOpt;
if (isObject(notMerge)) {
lazyUpdate = notMerge.lazyUpdate;
silent = notMerge.silent;
replaceMerge = notMerge.replaceMerge;
transitionOpt = notMerge.transition;
notMerge = notMerge.notMerge;
}
this[IN_MAIN_PROCESS_KEY] = true;
if (!this._model || notMerge) {
const optionManager = new OptionManager(this._api);
const theme = this._theme;
const ecModel = this._model = new GlobalModel();
ecModel.scheduler = this._scheduler;
ecModel.ssr = this._ssr;
ecModel.init(null, null, null, theme, this._locale, optionManager);
}
this._model.setOption(option as ECBasicOption, { replaceMerge }, optionPreprocessorFuncs);
const updateParams = {
seriesTransition: transitionOpt,
optionChanged: true
} as UpdateLifecycleParams;
if (lazyUpdate) {
this[PENDING_UPDATE] = {
silent: silent,
updateParams: updateParams
};
this[IN_MAIN_PROCESS_KEY] = false;
// `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
// It should wake it up to make sure zrender start to render at the next frame.
this.getZr().wakeUp();
}
else {
try {
prepare(this);
updateMethods.update.call(this, null, updateParams);
}
catch (e) {
this[PENDING_UPDATE] = null;
this[IN_MAIN_PROCESS_KEY] = false;
throw e;
}
// Ensure zr refresh sychronously, and then pixel in canvas can be
// fetched after `setOption`.
if (!this._ssr) {
// not use flush when using ssr mode.
this._zr.flush();
}
this[PENDING_UPDATE] = null;
this[IN_MAIN_PROCESS_KEY] = false;
flushPendingActions.call(this, silent);
triggerUpdatedEvent.call(this, silent);
}
}
/**
* @deprecated
*/
private setTheme(): void {
deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
}
// We don't want developers to use getModel directly.
private getModel(): GlobalModel {
return this._model;
}
getOption(): ECBasicOption {
return this._model && this._model.getOption() as ECBasicOption;
}
getWidth(): number {
return this._zr.getWidth();
}
getHeight(): number {
return this._zr.getHeight();
}
getDevicePixelRatio(): number {
return (this._zr.painter as CanvasPainter).dpr
/* eslint-disable-next-line */
|| (env.hasGlobalWindow && window.devicePixelRatio) || 1;
}
/**
* Get canvas which has all thing rendered
* @deprecated Use renderToCanvas instead.
*/
getRenderedCanvas(opts?: any): HTMLCanvasElement {
if (__DEV__) {
deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
}
return this.renderToCanvas(opts);
}
renderToCanvas(opts?: {
backgroundColor?: ZRColor
pixelRatio?: number
}): HTMLCanvasElement {
opts = opts || {};
const painter = this._zr.painter;
if (__DEV__) {
if (painter.type !== 'canvas') {
throw new Error('renderToCanvas can only be used in the canvas renderer.');
}
}
return (painter as CanvasPainter).getRenderedCanvas({
backgroundColor: (opts.backgroundColor || this._model.get('backgroundColor')) as ColorString,
pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
});
}
renderToSVGString(opts?: {
useViewBox?: boolean
}): string {
opts = opts || {};
const painter = this._zr.painter;
if (__DEV__) {
if (painter.type !== 'svg') {
throw new Error('renderToSVGString can only be used in the svg renderer.');
}
}
return (painter as SVGPainter).renderToString({
useViewBox: opts.useViewBox
});
}
/**
* Get svg data url
*/
getSvgDataURL(): string {
if (!env.svgSupported) {
return;
}
const zr = this._zr;
const list = zr.storage.getDisplayList();
// Stop animations
each(list, function (el: Element) {
el.stopAnimation(null, true);
});
return (zr.painter as SVGPainter).toDataURL();
}
getDataURL(opts?: {
// file type 'png' by default
type?: 'png' | 'jpeg' | 'svg',
pixelRatio?: number,
backgroundColor?: ZRColor,
// component type array
excludeComponents?: ComponentMainType[]
}): string {
if (this._disposed) {
disposedWarning(this.id);
return;
}
opts = opts || {};
const excludeComponents = opts.excludeComponents;
const ecModel = this._model;
const excludesComponentViews: ComponentView[] = [];
const self = this;
each(excludeComponents, function (componentType) {
ecModel.eachComponent({
mainType: componentType
}, function (component) {
const view = self._componentsMap[component.__viewId];
if (!view.group.ignore) {
excludesComponentViews.push(view);
view.group.ignore = true;
}
});
});
const url = this._zr.painter.getType() === 'svg'
? this.getSvgDataURL()
: this.renderToCanvas(opts).toDataURL(
'image/' + (opts && opts.type || 'png')
);
each(excludesComponentViews, function (view) {
view.group.ignore = false;
});
return url;
}
getConnectedDataURL(opts?: {
// file type 'png' by default
type?: 'png' | 'jpeg' | 'svg',
pixelRatio?: number,
backgroundColor?: ZRColor,
connectedBackgroundColor?: ZRColor
excludeComponents?: string[]
}): string {
if (this._disposed) {
disposedWarning(this.id);
return;
}
const isSvg = opts.type === 'svg';
const groupId = this.group;
const mathMin = Math.min;
const mathMax = Math.max;
const MAX_NUMBER = Infinity;
if (connectedGroups[groupId]) {
let left = MAX_NUMBER;
let top = MAX_NUMBER;
let right = -MAX_NUMBER;
let bottom = -MAX_NUMBER;
const canvasList: {dom: HTMLCanvasElement | string, left: number, top: number}[] = [];
const dpr = (opts && opts.pixelRatio) || this.getDevicePixelRatio();
each(instances, function (chart, id) {
if (chart.group === groupId) {
const canvas = isSvg
? (chart.getZr().painter as SVGPainter).getSvgDom().innerHTML
: chart.renderToCanvas(clone(opts));
const boundingRect = chart.getDom().getBoundingClientRect();
left = mathMin(boundingRect.left, left);
top = mathMin(boundingRect.top, top);
right = mathMax(boundingRect.right, right);
bottom = mathMax(boundingRect.bottom, bottom);
canvasList.push({
dom: canvas,
left: boundingRect.left,
top: boundingRect.top
});
}
});
left *= dpr;
top *= dpr;
right *= dpr;
bottom *= dpr;
const width = right - left;
const height = bottom - top;
const targetCanvas = platformApi.createCanvas();
const zr = zrender.init(targetCanvas, {
renderer: isSvg ? 'svg' : 'canvas'
});
zr.resize({
width: width,
height: height
});
if (isSvg) {
let content = '';
each(canvasList, function (item) {
const x = item.left - left;
const y = item.top - top;
content += '<g transform="translate(' + x + ','
+ y + ')">' + item.dom + '</g>';
});
(zr.painter as SVGPainter).getSvgRoot().innerHTML = content;
if (opts.connectedBackgroundColor) {
(zr.painter as SVGPainter).setBackgroundColor(opts.connectedBackgroundColor as string);
}
zr.refreshImmediately();
return (zr.painter as SVGPainter).toDataURL();
}
else {
// Background between the charts
if (opts.connectedBackgroundColor) {
zr.add(new graphic.Rect({
shape: {
x: 0,
y: 0,
width: width,
height: height
},
style: {
fill: opts.connectedBackgroundColor
}
}));
}
each(canvasList, function (item) {
const img = new graphic.Image({
style: {
x: item.left * dpr - left,
y: item.top * dpr - top,
image: item.dom
}
});
zr.add(img);
});
zr.refreshImmediately();
return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
}
}
else {
return this.getDataURL(opts);
}
}
/**
* Convert from logical coordinate system to pixel coordinate system.
* See CoordinateSystem#convertToPixel.
*/
convertToPixel(finder: ModelFinder, value: ScaleDataValue): number;
convertToPixel(finder: ModelFinder, value: ScaleDataValue[]): number[];
convertToPixel(finder: ModelFinder, value: ScaleDataValue | ScaleDataValue[]): number | number[] {
return doConvertPixel(this, 'convertToPixel', finder, value);
}
/**
* Convert from pixel coordinate system to logical coordinate system.
* See CoordinateSystem#convertFromPixel.
*/
convertFromPixel(finder: ModelFinder, value: number): number;
convertFromPixel(finder: ModelFinder, value: number[]): number[];
convertFromPixel(finder: ModelFinder, value: number | number[]): number | number[] {
return doConvertPixel(this, 'convertFromPixel', finder, value);
}
/**
* Is the specified coordinate systems or components contain the given pixel point.
* @param {Array|number} value
* @return {boolean} result
*/
containPixel(finder: ModelFinder, value: number[]): boolean {
if (this._disposed) {
disposedWarning(this.id);
return;
}
const ecModel = this._model;
let result: boolean;
const findResult = modelUtil.parseFinder(ecModel, finder);
each(findResult, function (models, key) {
key.indexOf('Models') >= 0 && each(models as ComponentModel[], function (model) {
const coordSys = (model as CoordinateSystemHostModel).coordinateSystem;
if (coordSys && coordSys.containPoint) {
result = result || !!coordSys.containPoint(value);
}
else if (key === 'seriesModels') {
const view = this._chartsMap[model.__viewId];
if (view && view.containPoint) {
result = result || view.containPoint(value, model as SeriesModel);
}
else {
if (__DEV__) {
warn(key + ': ' + (view
? 'The found component do not support containPoint.'
: 'No view mapping to the found component.'
));
}
}
}
else {
if (__DEV__) {
warn(key + ': containPoint is not supported');
}
}