-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathvchart.ts
More file actions
2366 lines (2126 loc) · 68.1 KB
/
Copy pathvchart.ts
File metadata and controls
2366 lines (2126 loc) · 68.1 KB
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
import type { ISeries } from '../series/interface/series';
import { arrayParser } from '../data/parser/array';
import type { ILayoutConstructor, LayoutCallBack } from '../layout/interface';
import type { IDataValues, IMarkStateSpec, IInitOption } from '../typings/spec/common';
// eslint-disable-next-line no-duplicate-imports
import { RenderModeEnum } from '../typings/spec/common';
import type { ISeriesConstructor } from '../series/interface';
import {
ChartTypeEnum,
type DimensionIndexOption,
type IChart,
type IChartConstructor,
type IChartOption,
type IChartSpecInfo,
type IChartSpecTransformer
} from '../chart/interface';
import type { IComponentConstructor } from '../component/interface';
// eslint-disable-next-line no-duplicate-imports
import { ComponentTypeEnum } from '../component/interface/type';
import type {
EventCallback,
EventQuery,
EventType,
ExtendEventParam,
IEvent,
IEventDispatcher
} from '../event/interface';
import type { IParserOptions, IFields, Transform } from '@visactor/vdataset';
// eslint-disable-next-line no-duplicate-imports
import { DataSet, dataViewParser, DataView } from '@visactor/vdataset';
import type { IGraphic, IStage, Stage } from '@visactor/vrender-core';
// eslint-disable-next-line no-duplicate-imports
import { vglobal } from '@visactor/vrender-core';
import { isString, isValid, isNil, array, specTransform, functionTransform, removeUndefined } from '../util';
import { createID } from '../util/id';
import { convertPoint } from '../util/space';
import { isTrueBrowser } from '../util/env';
import { warn } from '../util/debug';
import { getThemeObject } from '../util/theme/common';
import { mergeSpec, mergeSpecWithFilter } from '@visactor/vutils-extension';
import { Factory } from './factory';
import { Event } from '../event/event';
import { EventDispatcher } from '../event/event-dispatcher';
import type { GeoSourceType } from '../typings/geo';
import type { GeoSourceOption } from '../series/map/geo-source';
// eslint-disable-next-line no-duplicate-imports
import { getMapSource } from '../series/map/geo-source';
// eslint-disable-next-line no-duplicate-imports
import type { IMark, IMarkGraphic, MarkConstructor } from '../mark/interface';
import { registerDataSetInstanceParser, registerDataSetInstanceTransform } from '../data/register';
import { dataToDataView } from '../data/initialize';
import { copyDataView } from '../data/transforms/copy-data-view';
import type { ITooltipHandler } from '../typings/tooltip';
import type { ITooltip, Tooltip } from '../component/tooltip';
import type {
Datum,
IPoint,
IRegionQuerier,
IShowTooltipOption,
ISpec,
Maybe,
MaybeArray,
StringOrNumber
} from '../typings';
import { AnimationStateEnum } from '../animation/interface';
import type { IBoundsLike, ILogger } from '@visactor/vutils';
import { ThemeManager } from '../theme/theme-manager';
import type { ITheme } from '../theme';
import type { IModel, IUpdateDataResult, IUpdateSpecResult } from '../model/interface';
import { Compiler } from '../compile/compiler';
import type { IMorphConfig } from '../animation/spec';
import type { ILegend } from '../component/legend/interface';
import { getCanvasDataURL, URLToImage } from '../util/image';
import { ChartEvent } from '../constant/event';
import { DEFAULT_CHART_HEIGHT, DEFAULT_CHART_WIDTH } from '../constant/base';
// eslint-disable-next-line no-duplicate-imports
import {
isArray,
isEmpty,
Logger,
isFunction,
LoggerLevel,
isEqual,
get,
cloneDeep,
isObject,
throttle
} from '@visactor/vutils';
import type {
DataLinkAxis,
DataLinkSeries,
IGlobalConfig,
IVChart,
IVChartRenderOption,
UserEvent,
VChartRenderActionSource
} from './interface';
import { InstanceManager } from './instance-manager';
import type { IAxis } from '../component/axis';
import type { PopTipAttributes } from '@visactor/vrender-components/poptip/type';
import { setPoptipTheme } from '@visactor/vrender-components/poptip/register';
import {
calculateChartSize,
isUpdateSpecResultComponentOnly,
isUpdateSpecResultLocalOnly,
mergeUpdateResult
} from '../chart/util';
import { Region } from '../region/region';
import { Layout } from '../layout/base-layout';
import { registerGroupMark } from '../mark/group';
import { VCHART_UTILS } from './util';
import { ExpressionFunction } from './expression-function';
import { registerBrowserEnv, registerNodeEnv } from '../env';
import { mergeTheme, preprocessTheme } from '../util/theme';
import { darkTheme, registerTheme } from '../theme/builtin';
import type { IChartPluginService } from '../plugin/chart/interface';
import { ChartPluginService } from '../plugin/chart/plugin-service';
import type { IIndicator } from '../component/indicator';
import type { IGeoCoordinate } from '../component/geo';
import { registerGesturePlugin } from '../plugin/other';
import { registerElementHighlight } from '../interaction/triggers/element-highlight';
import { registerElementSelect } from '../interaction/triggers/element-select';
import type { IVChartPluginService } from '../plugin/vchart/interface';
import { VChartPluginService } from '../plugin/vchart/plugin-service';
import { RenderStateEnum } from '../constant/animate';
import type { ICrossHair } from '../component/crosshair';
import { releaseVRenderComponentSync } from '../component/base/release-vrender-component';
export class VChart implements IVChart {
readonly id = createID();
/**
* 按需注册图表和组件
* @param comps
* @since 1.5.1
*/
static useRegisters(comps: (() => void)[]) {
comps.forEach((fn: () => void) => {
if (typeof fn === 'function') {
// 确保元素是函数类型
fn();
} else {
console.error('Invalid function:', fn);
}
});
}
/**
* 注册自定义图表
* @param charts 图表类
* @description 若用于按需加载,1.5.1版本后,请统一使用 `useRegisters` API,例如:`VChart.useRegisters([registerLineChart])`。
*/
static useChart(charts: IChartConstructor[]) {
charts.forEach(c => Factory.registerChart(c.type, c));
}
/**
* 注册自定义系列
* @param series 系列类
* @description 若用于按需加载,1.5.1版本后,统一使用 `useRegisters` API,例如 `VChart.useRegisters([registerLineSeries])`。
*/
static useSeries(series: ISeriesConstructor[]) {
series.forEach(s => Factory.registerSeries(s.type, s));
}
/**
* 注册自定义组件
* @param components 组件类
* @description 若用于按需加载,1.5.1版本后,统一使用 `useRegisters` API,例如 `VChart.useRegisters([registerCartesianLinearAxis])`。
*/
static useComponent(components: IComponentConstructor[]) {
components.forEach(c => Factory.registerComponent(c.type, c));
}
/**
* 注册自定义 Mark
* @param marks Mark 图元类
*/
static useMark(marks: MarkConstructor[]) {
marks.forEach(m => Factory.registerMark(m.constructorType ?? m.type, m));
}
/**
* 注册自定义布局
* @param layouts 布局类
*/
static useLayout(layouts: ILayoutConstructor[]) {
layouts.forEach(l => Factory.registerLayout(l.type, l));
}
/**
* 注册 DataSet 数据方法
* @param name 数据 transform 方法名称
* @param transform 具体的 Transform 执行方法
*/
static registerDataSetTransform(name: string, transform: Transform) {
Factory.registerTransform(name, transform);
}
/**
* 注册函数(全局注册)
* @param key 函数名称
* @param fun 函数内容
*/
static registerFunction(key: string, fun: Function) {
if (!key || !fun) {
return;
}
ExpressionFunction.instance().registerFunction(key, fun);
}
/**
* 注销函数(全局注销)
* @param key 函数名称
*/
static unregisterFunction(key: string) {
if (!key) {
return;
}
ExpressionFunction.instance().unregisterFunction(key);
}
/**
* 获取函数(全局)
* @param key
* @returns
*/
static getFunction(key: string): Function | null {
if (!key) {
return null;
}
return ExpressionFunction.instance().getFunction(key);
}
/**
* 获取函数列表(全局获取)
* @returns
*/
static getFunctionList(): string[] | null {
return ExpressionFunction.instance().getFunctionNameList();
}
/**
* 注册地图数据
* @param key 地图名称
* @param source 地图数据
* @param option 地图数据配置
*/
static registerMap(key: string, source: GeoSourceType, option?: GeoSourceOption) {
const impl = Factory.getImplementInKey('registerMap');
impl && impl(key, source, option);
}
/**
* 注销地图数据
* @param key 地图名称
*/
static unregisterMap(key: string) {
const impl = Factory.getImplementInKey('unregisterMap');
impl && impl(key);
}
/**
* 根据地图名称获取地图数据
* @param key 地图名称
* @returns 地图数据
*/
static getMap(key: string): GeoSourceType {
return getMapSource(key);
}
/**
* 注册地图数据
* @param key 地图名称
* @param source 地图数据
* @param option 地图数据配置
*/
static registerSVG(key: string, source: GeoSourceType, option?: GeoSourceOption) {
const impl = Factory.getImplementInKey('registerSVG');
impl && impl(key, source, option);
}
/**
* 注销地图数据
* @param key 地图名称
*/
static unregisterSVG(key: string) {
const impl = Factory.getImplementInKey('unregisterSVG');
impl && impl(key);
}
/**
* 全局关闭 tooltip
* @param excludeId 可选,指定不需要关闭 tooltip 的实例 id
*/
static hideTooltip(excludeId: MaybeArray<number> = []): void {
InstanceManager.forEach(instance => instance?.hideTooltip?.(), excludeId);
}
/** 获取 Logger */
static getLogger(): ILogger {
return Logger.getInstance();
}
/** 图表实例管理器 */
static readonly InstanceManager = InstanceManager;
/** 主题管理器 */
static readonly ThemeManager = ThemeManager;
/** 全局配置 */
static globalConfig: IGlobalConfig = {
uniqueTooltip: true
};
/** 工具方法 */
static readonly Utils = VCHART_UTILS;
static readonly vglobal = vglobal;
protected _originalSpec: any;
protected _spec: any;
getSpec() {
return this._spec;
}
protected _specInfo: IChartSpecInfo;
getSpecInfo() {
return this._specInfo;
}
private _viewBox: IBoundsLike;
private _chart!: Maybe<IChart>;
private _chartSpecTransformer!: Maybe<IChartSpecTransformer>;
private _compiler: Compiler;
private _event: Maybe<IEvent>;
get event() {
return this._event;
}
private _userEvents: UserEvent[] = [];
private _eventDispatcher: Maybe<IEventDispatcher>;
private _dataSet!: Maybe<DataSet>;
getDataSet() {
return this._dataSet;
}
private _container?: HTMLElement;
private _canvas?: HTMLCanvasElement | OffscreenCanvas | string;
private _stage?: Stage;
private _autoSize: boolean = true;
private _option: IInitOption = {
mode: RenderModeEnum['desktop-browser'],
onError: (msg: string) => {
throw new Error(msg);
},
optimize: {
disableCheckGraphicWidthOutRange: true
}
};
private _currentSize: { width: number; height: number };
private _observer: ResizeObserver = null;
private _currentThemeName: string;
private _currentTheme: ITheme;
private _cachedProcessedTheme: ITheme;
private _onError?: (...args: any[]) => void;
private _context: any = {}; // 存放用户在model初始化前通过实例方法传入的配置等
private _isReleased: boolean;
private _exitingVRenderComponents?: Set<IGraphic>;
private _chartPlugin?: IChartPluginService;
private _vChartPlugin?: IVChartPluginService;
private _onResize?: () => void;
private _renderState: RenderStateEnum = RenderStateEnum.render;
protected _disableDimensionHoverEvent: boolean = false;
constructor(spec: ISpec, options: IInitOption) {
removeUndefined(options);
this._option = {
...this._option,
...options
};
if (options?.optimize) {
this._option.optimize = {
...this._option.optimize,
...options.optimize
};
}
this._onError = this._option?.onError;
const { dom, renderCanvas, mode, stage, poptip, ...restOptions } = this._option;
const isTrueBrowseEnv = isTrueBrowser(mode);
// 根据 mode 配置动态加载浏览器或 node 环境代码
if (isTrueBrowseEnv) {
registerBrowserEnv();
} else if (mode === 'node') {
registerNodeEnv();
}
if (isTrueBrowseEnv && dom) {
this._container = isString(dom) ? vglobal.getElementById(dom) : dom;
}
if (renderCanvas) {
this._canvas = renderCanvas;
}
if (stage) {
this._stage = stage as unknown as Stage; // FIXME: 等待 vrender 解决类型和接口不匹配的问题 @zhouxinyu
}
if (mode !== 'node' && !this._container && !this._canvas && !this._stage) {
this._option?.onError('please specify container or renderCanvas!');
return;
}
this._viewBox = this._option.viewBox;
this._currentThemeName = ThemeManager.getCurrentThemeName();
this._setNewSpec(spec);
this._updateCurrentTheme();
this._currentSize = this.getCurrentSize();
const pluginList: string[] = [];
if (poptip !== false) {
pluginList.push('poptipForText');
}
if (spec.type === ChartTypeEnum.sankey) {
// 桑基图默认记载滚动条组件
pluginList.push('scrollbar');
}
const logger = new Logger(this._option.logLevel ?? LoggerLevel.Error);
Logger.setInstance(logger);
if (this._option?.onError) {
logger.addErrorHandler((...args) => {
this._option?.onError?.(...args);
});
}
this._compiler = new Compiler(
{
dom: this._container ?? 'none',
canvas: renderCanvas
},
{
mode: this._option.mode,
stage,
pluginList,
...restOptions,
background: this._getBackground(),
onError: this._onError
}
);
this._compiler.setSize(this._currentSize.width, this._currentSize.height);
this._eventDispatcher = new EventDispatcher(this, this._compiler);
this._event = new Event(this._eventDispatcher, mode);
this._compiler.initView();
this._compiler.updateLayoutTag();
// TODO: 如果通过 updateSpec 更新主题字体的验证
// 设置全局字体
this._setFontFamilyTheme(this.getTheme('fontFamily') as string);
this._initDataSet(this._option.dataSet);
this._autoSize = isTrueBrowseEnv ? spec.autoFit ?? this._option.autoFit ?? true : false;
this._bindResizeEvent();
this._bindViewEvent();
this._initChartPlugin();
InstanceManager.registerInstance(this);
this._option.performanceHook?.afterCreateVChart?.(this);
}
/** 设置新 spec,返回是否成功 */
private _setNewSpec(spec: any, forceMerge?: boolean): boolean {
if (!spec) {
return false;
}
if (isString(spec)) {
spec = JSON.parse(spec);
}
if (forceMerge && this._originalSpec) {
spec = mergeSpec({}, this._originalSpec, spec);
}
this._originalSpec = spec;
this._spec = this._getSpecFromOriginalSpec();
return true;
}
private _getSpecFromOriginalSpec() {
// 转换在实例上注册的函数 + 深拷贝 spec,保证 _originalSpec 和 _spec 的不同
const spec = specTransform(this._originalSpec) as any;
// because of in data-init, data will be set as array;
spec.data = spec.data ?? [];
return spec;
}
private _initChartSpec(spec: any, actionSource: VChartRenderActionSource) {
// 如果用户注册了函数,在配置中替换相应函数名为函数内容
if (VChart.getFunctionList() && VChart.getFunctionList().length) {
spec = functionTransform(spec, VChart);
}
this._spec = spec;
if (!this._chartSpecTransformer) {
this._chartSpecTransformer = Factory.createChartSpecTransformer(
this._spec.type,
this._getChartOption(this._spec.type)
);
}
this._chartSpecTransformer?.transformSpec(this._spec);
// 插件生命周期
this._chartPluginApply('onAfterChartSpecTransform', this._spec, actionSource);
this._specInfo = this._chartSpecTransformer?.transformModelSpec(this._spec);
// 插件生命周期
this._chartPluginApply('onAfterModelSpecTransform', this._spec, this._specInfo, actionSource);
}
private _updateSpecInfo() {
if (!this._chartSpecTransformer) {
this._chartSpecTransformer = Factory.createChartSpecTransformer(
this._spec.type,
this._getChartOption(this._spec.type)
);
}
this._specInfo = this._chartSpecTransformer?.createSpecInfo(this._spec);
}
private _initChart(spec: any) {
if (!this._compiler) {
this._option?.onError('compiler is not initialized');
return;
}
if (this._chart) {
this._option?.onError('chart is already initialized');
return;
}
// 放到这里而不是放到chart内的考虑
// 用户spec更新,也许会有core上图表实例的内容存在
// 如果要支持spec的类似Proxy监听,更新逻辑应当从这一层开始。如果在chart上做,就需要在再向上发送spec更新消息,不是很合理。
// todo: 问题1 存不存在 chart 需要在这个阶段处理的特殊字段?目前没有,但是理论上可以有?
const chart = Factory.createChart(spec.type, spec, this._getChartOption(spec.type));
if (!chart) {
this._option?.onError('init chart fail');
return;
}
this._chart = chart;
this._chart.setCanvasRect(this._currentSize.width, this._currentSize.height);
this._chart.created(this._chartSpecTransformer);
this._chart.init();
this._event.emit(ChartEvent.initialized, {
chart,
vchart: this
});
}
private _releaseData() {
if (this._dataSet) {
// Object.values(this._dataSet.dataViewMap).forEach(d => {
// d.target.removeAllListeners();
// d.destroy();
// });
this._dataSet.dataViewMap = {};
this._dataSet = null;
}
}
private _bindViewEvent() {
if (!this._compiler) {
return;
}
(this._compiler.getStage()?.getTimeline() as any)?.on('animationEnd', () => {
this._event.emit(ChartEvent.animationFinished, {
chart: this._chart,
vchart: this
});
});
}
private _bindResizeEvent() {
if (this._autoSize) {
this._onResize = throttle(this._doResize, this._option.resizeDelay ?? 100);
if (this._container) {
const ResizeObserverWindow: any = window.ResizeObserver;
if (ResizeObserverWindow) {
this._observer = new ResizeObserverWindow(this._onResize);
this._observer?.observe(this._container);
}
}
window.addEventListener('resize', this._onResize);
}
}
private _unBindResizeEvent() {
if (this._autoSize) {
window.removeEventListener('resize', this._onResize);
if (this._observer) {
this._observer.disconnect();
this._observer = null;
}
}
}
getCurrentSize() {
return calculateChartSize(
this._spec,
{
container: this._container,
canvas: this._canvas,
mode: this._getMode(),
modeParams: this._option.modeParams
},
{
width: this._currentSize?.width ?? DEFAULT_CHART_WIDTH,
height: this._currentSize?.height ?? DEFAULT_CHART_HEIGHT
}
);
}
private _doResize = () => {
const { width, height } = this.getCurrentSize();
if (this._currentSize.width !== width || this._currentSize.height !== height) {
this._currentSize = { width, height };
this.resizeSync(width, height);
}
};
private _initDataSet(dataSet?: DataSet) {
if (dataSet instanceof DataSet) {
this._dataSet = dataSet;
} else {
this._dataSet = new DataSet();
}
registerDataSetInstanceParser(this._dataSet, 'dataview', dataViewParser);
registerDataSetInstanceParser(this._dataSet, 'array', arrayParser);
registerDataSetInstanceTransform(this._dataSet, 'copyDataView', copyDataView);
// 注册 dataset transform
for (const key in Factory.transforms) {
registerDataSetInstanceTransform(this._dataSet, key, Factory.transforms[key]);
}
// 注册 dataview parser
for (const key in Factory.dataParser) {
registerDataSetInstanceParser(this._dataSet, key, Factory.dataParser[key]);
}
}
/** 在修改图表配置后重新渲染 */
updateCustomConfigAndRerender(
updateSpecResult: IUpdateSpecResult | (() => IUpdateSpecResult),
sync?: boolean,
option: IVChartRenderOption = {}
) {
if (this._isReleased || !updateSpecResult) {
return undefined;
}
if (isFunction(updateSpecResult)) {
updateSpecResult = (updateSpecResult as () => IUpdateSpecResult)();
}
if ((updateSpecResult as IUpdateSpecResult).reAnimate) {
this.stopAnimation();
this._updateAnimateState(true);
}
this._reCompile(updateSpecResult as IUpdateSpecResult, option.morphConfig);
if (isUpdateSpecResultLocalOnly(updateSpecResult as IUpdateSpecResult)) {
return this as unknown as IVChart;
}
if (sync) {
return this._renderSync(option);
}
return this._renderAsync(option);
}
/** 执行自定义的回调修改图表配置,并重新编译(不渲染) */
protected _updateCustomConfigAndRecompile(updateSpecResult: IUpdateSpecResult, option: IVChartRenderOption = {}) {
if (!updateSpecResult) {
return false;
}
this._reCompile(updateSpecResult, option.morphConfig);
return this._beforeRender(option);
}
protected _reCompile(updateResult: IUpdateSpecResult, morphConfig?: IMorphConfig) {
const shouldRestoreUserEvents = updateResult.reMake && !!this._chart;
if (updateResult.reMake) {
this._releaseData();
this._initDataSet();
(this._chart as any)?.release(false);
this._chart = null as unknown as IChart;
}
if (updateResult.reTransformSpec) {
// 释放图表等等
this._chartSpecTransformer = null;
}
// 卸载了chart之后再设置主题 避免多余的reInit
if (updateResult.changeTheme) {
this._setCurrentTheme();
this._setFontFamilyTheme(this.getTheme('fontFamily') as string);
} else if (updateResult.changeBackground) {
this._compiler?.setBackground(this._getBackground());
}
if (updateResult.reMake) {
const cacheGrammarForMorph = this.isAnimationEnable() && morphConfig?.morph !== false;
// morph 需要保留上一轮 simple mark product,后续 compiler.compile 会统一 diff 并释放未使用的旧 product。
this._compiler?.releaseGrammar(!cacheGrammarForMorph);
// chart 内部事件 模块自己必须删除
// 内部模块删除事件时,调用了event Dispatcher.release() 导致用户事件被一起删除
// 外部事件现在需要重新添加
if (shouldRestoreUserEvents) {
this._userEvents.forEach(e => this._event?.on(e.eType as any, e.query as any, e.handler as any));
}
} else if (updateResult.reCompile) {
// recompile
// 清除之前的所有 compile 内容
this._compiler?.clear({ chart: this._chart, vChart: this });
// 重新compile
this._compiler?.compile({ chart: this._chart, vChart: this });
}
if (updateResult.reSize) {
const { width, height } = this.getCurrentSize();
this._currentSize = { width, height };
this._chart?.onResize(width, height, false);
this._compiler?.resize(width, height, false);
}
}
/** 渲染之前的步骤,返回是否成功 */
protected _beforeRender(option: IVChartRenderOption = {}): boolean {
// 如果 vchart 实例已经卸载,终止渲染
if (this._isReleased) {
return false;
}
// 如果图表已经实例化,跳过该步骤
if (this._chart) {
return true;
}
const { transformSpec, actionSource } = option;
if (transformSpec) {
// 初始化图表 spec
this._initChartSpec(this._spec, 'render');
// 插件生命周期
}
this._chartPluginApply('onBeforeInitChart', this._spec, actionSource);
// 实例化图表
this._option.performanceHook?.beforeInitializeChart?.(this);
this._initChart(this._spec);
this._option.performanceHook?.afterInitializeChart?.(this);
// 如果实例化失败,终止渲染
if (!this._chart || !this._compiler) {
return false;
}
this._chartPluginApply('onAfterInitChart', this._spec, actionSource);
// compile
this._option.performanceHook?.beforeCompileToVGrammar?.(this);
this._compiler.compile({ chart: this._chart, vChart: this }, option);
this._option.performanceHook?.afterCompileToVGrammar?.(this);
return true;
}
/** 渲染之后的步骤 */
protected _afterRender(): boolean {
if (this._isReleased) {
return false;
}
this._event.emit(ChartEvent.rendered, {
chart: this._chart,
vchart: this
});
return true;
}
/**
* **同步方法** 渲染图表。
* @param morphConfig 图表 morph 动画配置,可选
* @returns VChart 实例
*/
renderSync(morphConfig?: IMorphConfig) {
return this._renderSync({
morphConfig,
transformSpec: true,
actionSource: 'render'
});
}
/**
* **异步方法** 渲染图表。
* @param morphConfig 图表 morph 动画配置,可选
* @returns VChart 实例
*/
async renderAsync(morphConfig?: IMorphConfig) {
return this._renderAsync({
morphConfig,
transformSpec: true,
actionSource: 'render'
});
}
protected _renderSync = (option: IVChartRenderOption = {}) => {
const self = this as unknown as IVChart;
if (!this._beforeRender(option)) {
return self;
}
// 填充数据绘图
this._compiler?.render(option.morphConfig);
this._updateAnimateState(false);
this._afterRender();
return self;
};
protected async _renderAsync(option: IVChartRenderOption = {}) {
return this._renderSync(option);
}
private _updateAnimateState(initial?: boolean) {
if (this.isAnimationEnable()) {
const updateGraphicAnimationState = (graphic: IMarkGraphic) => {
const diffState = graphic.context?.diffState;
if (initial) {
return diffState === 'exit' ? AnimationStateEnum.none : AnimationStateEnum.appear;
}
return diffState;
};
this._chart?.getAllRegions().forEach(region => {
region.updateAnimateStateCallback(updateGraphicAnimationState);
});
this._chart?.getAllComponents().forEach(component => {
component.updateAnimateStateCallback(updateGraphicAnimationState);
});
}
}
/**
* 销毁图表
*/
release() {
if ((this._onResize as any)?.cancel) {
(this._onResize as any).cancel();
}
this._chartPluginApply('releaseAll');
this._chartPlugin = null;
this._chartSpecTransformer = null;
this._forceReleaseExitingVRenderComponents();
this._chart?.release();
// eventDispatcher 的release 依赖 compiler
this._eventDispatcher?.release();
this._compiler?.release();
this._unBindResizeEvent();
// resetID(); // 为什么要重置ID呢?
this._releaseData();
this._onError = null;
this._onResize = null;
this._container = null;
this._currentTheme = null;
this._cachedProcessedTheme = null;
this._option = null;
this._chart = null;
this._compiler = null;
this._spec = null;
this._specInfo = null;
this._originalSpec = null;
// this._option = null;
this._userEvents = null;
this._event = null;
this._eventDispatcher = null;
this._isReleased = true;
InstanceManager.unregisterInstance(this);
}
_registerExitingVRenderComponent(component: IGraphic) {
this._exitingVRenderComponents = this._exitingVRenderComponents ?? new Set();
this._exitingVRenderComponents.add(component);
}
_unregisterExitingVRenderComponent(component: IGraphic) {
this._exitingVRenderComponents?.delete(component);
}
private _forceReleaseExitingVRenderComponents() {
if (!this._exitingVRenderComponents?.size) {
return;
}
this._exitingVRenderComponents.forEach(component => {
releaseVRenderComponentSync(component);
});
this._exitingVRenderComponents.clear();
}
/**
* **异步方法** 更新数据。
* @param id 数据 id
* @param data 数据值
* @param parserOptions 数据参数
* @returns VChart 实例
*/
async updateData(
id: StringOrNumber,
data: DataView | Datum[] | string,
parserOptions?: IParserOptions,
userUpdateOptions?: IUpdateDataResult
): Promise<IVChart> {
return this.updateDataSync(id, data, parserOptions, userUpdateOptions);
}
private _updateDataById(id: StringOrNumber, data: DataView | Datum[] | string, parserOptions?: IParserOptions) {
const preDV = this._spec.data.find((dv: any) => dv.name === id || dv.id === id);
if (preDV) {
if (preDV.id === id) {
preDV.values = data;
} else if (preDV.name === id) {
preDV.parse(data, parserOptions);
}
} else {
if (isArray(data)) {
this._spec.data.push({
id,
values: data
});
} else {
this._spec.data.push(data);
}
}
}
/**
* **异步方法** 批量更新数据。
* @param list 待更新的数据列表
* @returns VChart 实例
*/
async updateDataInBatches(list: { id: string; data: Datum[]; options?: IParserOptions }[]): Promise<IVChart> {
if (this._chart) {
this._chart.updateFullData(
list.map(({ id, data, options }) => {
return { id, values: data, parser: options };
})
);
this._chart.updateGlobalScaleDomain();
this._compiler.render();
return this as unknown as IVChart;
}
this._spec.data = array(this._spec.data);
list.forEach(({ id, data, options }) => {
this._updateDataById(id, data, options);
});
return this as unknown as IVChart;
}
/**
* **同步方法** 更新数据
* @param id 数据 id
* @param data 数据值
* @param parserOptions 数据参数
* @returns VChart 实例
*/
updateDataSync(
id: StringOrNumber,
data: DataView | Datum[] | string,
parserOptions?: IParserOptions,
userUpdateOptions?: IUpdateDataResult
) {
if (this._isReleased) {
return this as unknown as IVChart;
}
this._reSetRenderState();
if (isNil(this._dataSet)) {
return this as unknown as IVChart;
}
if (this._chart) {
this._chart.updateData(id, data, true, parserOptions);
if (userUpdateOptions?.reAnimate) {
this.stopAnimation();
this._updateAnimateState(true);
}
this._compiler.render();
return this as unknown as IVChart;
}
this._spec.data = array(this._spec.data);