-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
plot.ts
1520 lines (1416 loc) · 44.5 KB
/
plot.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
import { Vector2 } from '@antv/coord';
import { DisplayObject, IAnimation as GAnimation, Rect } from '@antv/g';
import { deepMix, upperFirst } from '@antv/util';
import { group } from 'd3-array';
import { format } from 'd3-format';
import { mapObject } from '../utils/array';
import { ChartEvent } from '../utils/event';
import {
appendTransform,
copyAttributes,
defined,
error,
maybeSubObject,
subObject,
useMemo,
} from '../utils/helper';
import { G2Element, select, Selection } from '../utils/selection';
import { inferComponent, renderComponent } from './component';
import {
AREA_CLASS_NAME,
COMPONENT_CLASS_NAME,
ELEMENT_CLASS_NAME,
LABEL_CLASS_NAME,
LABEL_LAYER_CLASS_NAME,
MAIN_LAYER_CLASS_NAME,
PLOT_CLASS_NAME,
VIEW_CLASS_NAME,
} from './constant';
import { coordinate2Transform, createCoordinate } from './coordinate';
import { computeLayout, placeComponents } from './layout';
import { useLibrary } from './library';
import { initializeMark } from './mark';
import {
applyScale,
inferScale,
syncFacetsScales,
useRelationScale,
} from './scale';
import { applyDataTransform } from './transform';
import {
G2MarkState,
G2ViewDescriptor,
G2ViewInstance,
Primitive,
} from './types/common';
import {
Animation,
AnimationComponent,
Composition,
CompositionComponent,
Interaction,
InteractionComponent,
LabelTransform,
LabelTransformComponent,
Shape,
ShapeComponent,
Theme,
ThemeComponent,
} from './types/component';
import { CompositeMark, Mark, MarkComponent, SingleMark } from './types/mark';
import {
G2AnimationOptions,
G2CompositionOptions,
G2Context,
G2GuideComponentOptions,
G2InteractionOptions,
G2LabelTransformOptions,
G2Library,
G2Mark,
G2MarkOptions,
G2ScaleOptions,
G2ShapeOptions,
G2ThemeOptions,
G2View,
G2ViewTree,
} from './types/options';
export async function plot<T extends G2ViewTree>(
options: T,
selection: Selection,
library: G2Library,
context: G2Context,
): Promise<any> {
const [useComposition] = useLibrary<
G2CompositionOptions,
CompositionComponent,
Composition
>('composition', library);
const [useInteraction] = useLibrary<
G2InteractionOptions,
InteractionComponent,
Interaction
>('interaction', library);
// Some helper functions.
const marks = new Set(
Object.keys(library)
.map((d) => /mark\.(.*)/.exec(d)?.[1])
.filter(defined),
);
const typeOf = (node: G2ViewTree) => {
const { type } = node;
if (typeof type === 'function') {
// @ts-ignore
const { props = {} } = type;
const { composite = true } = props;
if (composite) return 'mark';
}
return typeof type === 'string' && marks.has(type) ? 'mark' : type;
};
const isMark = (node: G2ViewTree) => typeOf(node) === 'mark';
const isStandardView = (node: G2ViewTree) => typeOf(node) === 'standardView';
const transform = (node: G2ViewTree) => {
if (isStandardView(node)) return [node];
const type = typeOf(node);
const composition = useComposition({ type });
return composition(node);
};
// Some temporary variables help parse the view tree.
const views: G2ViewDescriptor[] = [];
const viewNode = new Map<G2ViewDescriptor, G2ViewTree>();
const nodeState = new Map<G2ViewTree, Map<G2Mark, G2MarkState>>();
const discovered: G2ViewTree[] = [options];
const nodeGenerators: Generator<G2ViewTree, void, void>[] = [];
while (discovered.length) {
const node = discovered.shift();
if (isStandardView(node)) {
// Initialize view to get data to be visualized. If the marks
// of the view have already been initialized (facet view),
// initialize the view based on the initialized mark states,
// otherwise initialize it from beginning.
const state = nodeState.get(node);
const [view, children] = state
? initializeState(state, node, library)
: await initializeView(node, library);
viewNode.set(view, node);
views.push(view);
// Transform children, they will be transformed into
// standardView if they are mark or view node.
const transformedNodes = children
.flatMap(transform)
.map((d) => coordinate2Transform(d, library));
discovered.push(...transformedNodes);
// Only StandardView can be treated as facet and it
// should sync position scales among facets normally.
if (transformedNodes.every(isStandardView)) {
const states = await Promise.all(
transformedNodes.map((d) => initializeMarks(d, library)),
);
// Note!!!
// This will mutate scales for marks.
syncFacetsScales(states);
for (let i = 0; i < transformedNodes.length; i++) {
const nodeT = transformedNodes[i];
const state = states[i];
nodeState.set(nodeT, state);
}
}
} else {
// Apply transform to get data in advance for non-mark composition
// node, which makes sure that composition node can preprocess the
// data to produce more nodes based on it.
const n = isMark(node) ? node : await applyTransform(node, library);
const N = transform(n);
if (Array.isArray(N)) discovered.push(...N);
else if (typeof N === 'function') nodeGenerators.push(N());
}
}
context.emitter.emit(ChartEvent.BEFORE_PAINT);
// Plot chart.
const enterContainer = new Map<G2ViewDescriptor, DisplayObject>();
const updateContainer = new Map<G2ViewDescriptor, DisplayObject>();
const transitions: GAnimation[] = [];
selection
.selectAll(className(VIEW_CLASS_NAME))
.data(views, (d) => d.key)
.join(
(enter) =>
enter
.append('g')
.attr('className', VIEW_CLASS_NAME)
.attr('id', (view) => view.key)
.call(applyTranslate)
.each(function (view) {
plotView(view, select(this), transitions, library);
enterContainer.set(view, this);
}),
(update) =>
update.call(applyTranslate).each(function (view) {
plotView(view, select(this), transitions, library);
updateContainer.set(view, this);
}),
(exit) =>
exit
.each(function () {
// Remove existed interactions.
const interactions = this['nameInteraction'].values();
for (const interaction of interactions) {
interaction.destroy();
}
})
.remove(),
);
// Apply interactions.
const viewInstanceof = (
viewContainer: Map<G2ViewDescriptor, DisplayObject>,
) => {
return Array.from(viewContainer.entries()).map(([view, container]) => ({
view,
container,
options: viewNode.get(view),
update: createUpdateView(select(container), library, context),
}));
};
// Interactions for enter views.
const enterViewInstances = viewInstanceof(enterContainer);
for (const target of enterViewInstances) {
const { options } = target;
// A Map index interaction by interaction name.
const nameInteraction = new Map();
target.container['nameInteraction'] = nameInteraction;
// Apply interactions.
for (const option of inferInteraction(options)) {
const interaction = useInteraction(option);
const destroy = interaction(target, enterViewInstances, context.emitter);
nameInteraction.set(option.type, { destroy });
}
}
// Interactions for update views.
const updateViewInstances = viewInstanceof(updateContainer);
for (const target of updateViewInstances) {
const { options, container } = target;
const nameInteraction = container['nameInteraction'];
for (const option of inferInteraction(options)) {
// Remove interaction for existed views.
const prevInteraction = nameInteraction.get(option.type);
if (prevInteraction) prevInteraction.destroy?.();
// Apply new interaction.
const interaction = useInteraction(option);
const destroy = interaction(target, updateViewInstances, context.emitter);
nameInteraction.set(options.type, { destroy });
}
}
// Author animations.
const { width, height } = options;
const keyframes = [];
for (const nodeGenerator of nodeGenerators) {
// Delay the rendering of animation keyframe. Different animation
// created by different nodeGenerator will play in the same time.
// eslint-disable-next-line no-async-promise-executor
const keyframe = new Promise<void>(async (resolve) => {
for (const node of nodeGenerator) {
const sizedNode = { width, height, ...node };
await plot(sizedNode, selection, library, context);
}
resolve();
});
keyframes.push(keyframe);
}
context.views = views;
context.animations = transitions;
context.emitter.emit(ChartEvent.AFTER_PAINT);
// Note!!!
// The returned promise will never resolved if one of nodeGenerator
// never stop to yield node, which may created by a keyframe composition
// with iteration count set to infinite.
const finished = transitions
.filter(defined)
.map(cancel)
.map((d) => d.finished);
return Promise.all([...finished, ...keyframes]);
}
function applyTranslate(selection: Selection) {
selection.style(
'transform',
(d) => `translate(${d.layout.x}, ${d.layout.y})`,
);
}
function createUpdateView(
selection: Selection,
library: G2Library,
context: G2Context,
): G2ViewInstance['update'] {
return async (newOptions) => {
const transitions = [];
const [newView, newChildren] = await initializeView(newOptions, library);
plotView(newView, selection, transitions, library);
updateTooltip(selection, newOptions, newView, library, context);
for (const child of newChildren) {
plot(child, selection, library, context);
}
return { options: newOptions, view: newView };
};
}
function updateTooltip(selection, options, view, library, context) {
const [useInteraction] = useLibrary<
G2InteractionOptions,
InteractionComponent,
Interaction
>('interaction', library);
// Instances for tooltip.
const container = selection.node();
const nameInteraction = container['nameInteraction'];
const { interaction } = options;
const tooltipOptions = inferInteraction(interaction).find(
(d) => d.type === 'tooltip',
);
// Destroy older tooltip.
const tooltip = nameInteraction.get('tooltip');
if (!tooltip) return;
tooltip.destroy?.();
// Apply new tooltip interaction.
const applyTooltip = useInteraction(tooltipOptions);
const target = {
options,
view,
container: selection.node(),
update: (options) => Promise.resolve(options),
};
applyTooltip(target, [], context.emitter);
}
async function initializeView(
options: G2View,
library: G2Library,
): Promise<[G2ViewDescriptor, G2ViewTree[]]> {
const flattenOptions = await transformMarks(options, library);
const mergedOptions = bubbleOptions(flattenOptions);
// @todo Remove this.
// !!! NOTE: Mute original view options.
// Update interaction and coordinate for this view.
options.interaction = mergedOptions.interaction;
options.coordinate = mergedOptions.coordinate;
const transformedOptions = coordinate2Transform(mergedOptions, library);
const state = await initializeMarks(transformedOptions, library);
return initializeState(state, transformedOptions, library);
}
function bubbleOptions(options: G2View): G2View {
const {
coordinate: viewCoordinate = {},
interaction: viewInteraction = {},
marks,
...rest
} = options;
const markCoordinates = marks.map((d) => d.coordinate || {});
const markInteractions = marks.map((d) => d.interaction || {});
const newCoordinate = [...markCoordinates, viewCoordinate].reduceRight(
(prev, cur) => deepMix(prev, cur),
{},
);
const newInteraction = [viewInteraction, ...markInteractions].reduce(
(prev, cur) => deepMix(prev, cur),
{},
);
return {
...rest,
marks,
coordinate: newCoordinate,
interaction: newInteraction,
};
}
async function transformMarks(
options: G2View,
library: G2Library,
): Promise<G2View> {
const [useMark, createMark] = useLibrary<G2MarkOptions, MarkComponent, Mark>(
'mark',
library,
);
const { marks } = options;
const flattenMarks = [];
const discovered = [...marks];
// Pre order traversal.
while (discovered.length) {
const [node] = discovered.splice(0, 1);
// Apply data transform to get data.
const mark = (await applyTransform(node, library)) as G2Mark;
const { type = error('G2Mark type is required.'), key } = mark;
const { props = {} } = createMark(type);
const { composite = true } = props;
if (!composite) flattenMarks.push(mark);
else {
// Convert composite mark to marks.
const marks = await (
useMark as (options: G2MarkOptions) => CompositeMark
)(mark)(options);
const M = Array.isArray(marks) ? marks : [marks];
discovered.unshift(...M.map((d, i) => ({ ...d, key: `${key}-${i}` })));
}
}
return { ...options, marks: flattenMarks };
}
async function initializeMarks(
options: G2View,
library: G2Library,
): Promise<Map<G2Mark, G2MarkState>> {
const [useTheme] = useLibrary<G2ThemeOptions, ThemeComponent, Theme>(
'theme',
library,
);
const [, createMark] = useLibrary<G2MarkOptions, MarkComponent, Mark>(
'mark',
library,
);
const {
theme: partialTheme,
marks: partialMarks,
coordinates = [],
} = options;
const theme = useTheme(inferTheme(partialTheme));
const markState = new Map<G2Mark, G2MarkState>();
// Initialize channels for marks.
for (const markOptions of partialMarks) {
const { type } = markOptions;
const { props = {} } = createMark(type);
const markAndState = await initializeMark(markOptions, props, library);
if (markAndState) {
const [initializedMark, state] = markAndState;
markState.set(initializedMark, state);
}
}
// Group channels by scale key, each group has scale.
const scaleChannels = group(
Array.from(markState.values()).flatMap((d) => d.channels),
({ scaleKey }) => scaleKey,
);
// Infer scale for each channel groups.
for (const channels of scaleChannels.values()) {
// Merge scale options for these channels.
const scaleOptions = channels.reduce(
(total, { scale }) => deepMix(total, scale),
{},
);
// Use the fields of the first channel as the title.
const { values: FV } = channels[0];
const fields = Array.from(new Set(FV.map((d) => d.field).filter(defined)));
const options = deepMix(
{
guide: { title: fields.length === 0 ? undefined : fields },
field: fields[0],
},
scaleOptions,
);
// Use the name of the first channel as the scale name.
const { name } = channels[0];
const values = channels.flatMap(({ values }) => values.map((d) => d.value));
const scale = inferScale(
name,
values,
options,
coordinates,
theme,
library,
);
channels.forEach((channel) => (channel.scale = scale));
}
return markState;
}
function initializeState(
markState: Map<G2Mark, G2MarkState>,
options: G2View,
library: G2Library,
): [G2ViewDescriptor, G2ViewTree[]] {
const [useMark] = useLibrary<G2MarkOptions, MarkComponent, Mark>(
'mark',
library,
);
const [useTheme] = useLibrary<G2ThemeOptions, ThemeComponent, Theme>(
'theme',
library,
);
const [useLabelTransform] = useLibrary<
G2LabelTransformOptions,
LabelTransformComponent,
LabelTransform
>('labelTransform', library);
const {
key,
frame = false,
theme: partialTheme,
clip,
style = {},
labelTransform = [],
} = options;
const theme = useTheme(inferTheme(partialTheme));
// Infer components and compute layout.
const states = Array.from(markState.values());
const scales = Array.from(
new Set(states.flatMap((d) => d.channels.map((d) => d.scale))),
);
const components = inferComponent(
inferComponentScales(Array.from(scales), states, markState),
options,
library,
);
const layout = computeLayout(components, options);
const coordinate = createCoordinate(layout, options, library);
const framedStyle = frame
? deepMix({ mainLineWidth: 1, mainStroke: '#000' }, style)
: style;
// Place components and mutate their bbox.
placeComponents(components, coordinate, layout);
// Calc data to be rendered for each mark.
// @todo More readable APIs for Container which stays
// the same style with JS standard and lodash APIs.
// @todo More proper way to index scale for different marks.
const scaleInstance = {};
const children = [];
for (const [mark, state] of markState.entries()) {
const {
// scale,
// Callback to create children options based on this mark.
children: createChildren,
// The total count of data (both show and hide)for this facet.
// This is for unit visualization to sync data domain.
dataDomain,
modifier,
key: markKey,
} = mark;
const { index, channels, tooltip } = state;
const scale = Object.fromEntries(
channels.map(({ name, scale }) => [name, scale]),
);
// Transform abstract value to visual value by scales.
const markScaleInstance = mapObject(scale, (options) => {
return useRelationScale(options, library);
});
Object.assign(scaleInstance, markScaleInstance);
const value = applyScale(channels, markScaleInstance);
// Calc points and transformation for each data,
// and then transform visual value to visual data.
const calcPoints = (useMark as (options: G2MarkOptions) => SingleMark)(
mark,
);
const [I, P, S] = filterValid(
calcPoints(index, markScaleInstance, value, coordinate),
);
const count = dataDomain || I.length;
const T = modifier ? modifier(P, count, layout) : [];
const titleOf = (i) => tooltip.title?.[i]?.value;
const itemsOf = (i) => tooltip.items.map((V) => V[i]);
const visualData: Record<string, any>[] = I.map((d, i) => {
const datum = {
points: P[i],
transform: T[i],
index: d,
markKey,
viewKey: key,
...(tooltip && {
title: titleOf(d),
items: itemsOf(d),
}),
};
for (const [k, V] of Object.entries(value)) {
datum[k] = V[d];
if (S) datum[`series${upperFirst(k)}`] = S[i].map((i) => V[i]);
}
if (S) datum['seriesIndex'] = S[i];
if (S && tooltip) {
datum['seriesItems'] = S[i].map((si) => itemsOf(si));
datum['seriesTitle'] = S[i].map((si) => titleOf(si));
}
return datum;
});
state.data = visualData;
state.index = I;
// Create children options by children callback,
// and then propagate data to each child.
const markChildren = createChildren?.(
visualData,
markScaleInstance,
layout,
);
children.push(...(markChildren || []));
}
const view = {
layout,
theme,
coordinate,
components,
markState,
key,
clip,
scale: scaleInstance,
style: framedStyle,
labelTransform: composeLabelTransform(
labelTransform.map(useLabelTransform),
),
};
return [view, children];
}
async function plotView(
view: G2ViewDescriptor,
selection: Selection,
transitions: GAnimation[],
library: G2Library,
): Promise<void> {
const { components, theme, layout, markState, coordinate, key, style, clip } =
view;
// Render background for the different areas.
const { x, y, width, height, ...rest } = layout;
const areaKeys = ['view', 'plot', 'main', 'content'];
const I = areaKeys.map((_, i) => i);
const sizeKeys = ['a', 'margin', 'padding', 'inset'];
const areaStyles = areaKeys.map((d) =>
maybeSubObject(Object.assign({}, theme, style), d),
);
const areaSizes = sizeKeys.map((d) => subObject(rest, d));
const styleArea = (selection) =>
selection
.style('x', (i) => areaLayouts[i].x)
.style('y', (i) => areaLayouts[i].y)
.style('width', (i) => areaLayouts[i].width)
.style('height', (i) => areaLayouts[i].height)
.each(function (i) {
applyStyle(select(this), areaStyles[i]);
});
let px = 0;
let py = 0;
let pw = width;
let ph = height;
const areaLayouts = I.map((i) => {
const size = areaSizes[i];
const { left = 0, top = 0, bottom = 0, right = 0 } = size;
px += left;
py += top;
pw -= left + right;
ph -= top + bottom;
return {
x: px,
y: py,
width: pw,
height: ph,
};
});
selection
.selectAll(className(AREA_CLASS_NAME))
.data(
// Only render area with defined style.
I.filter((i) => defined(areaStyles[i])),
(i) => areaKeys[i],
)
.join(
(enter) =>
enter
.append('rect')
.attr('className', AREA_CLASS_NAME)
.style('zIndex', -2)
.call(styleArea),
(update) => update.call(styleArea),
(exit) => exit.remove(),
);
const animationExtent = computeAnimationExtent(markState);
const componentAnimateOptions = animationExtent
? { duration: animationExtent[1] }
: false;
// Render components.
// @todo renderComponent return ctor and options.
const componentsTransitions = selection
.selectAll(className(COMPONENT_CLASS_NAME))
.data(components, (d, i) => `${d.type}-${i}`)
.join(
(enter) =>
enter
.append('g')
.style('zIndex', ({ zIndex }) => zIndex || -1)
.attr('className', COMPONENT_CLASS_NAME)
.append((options) =>
renderComponent(
deepMix({ animate: componentAnimateOptions }, options),
coordinate,
theme,
library,
markState,
),
),
(update) =>
update.transition(function (options: G2GuideComponentOptions) {
const { preserve = false } = options;
if (preserve) return;
const newComponent = renderComponent(
deepMix({ animate: componentAnimateOptions }, options),
coordinate,
theme,
library,
markState,
);
const { attributes } = newComponent;
const [node] = this.childNodes;
return node.update(attributes);
}),
)
.transitions();
transitions.push(...componentsTransitions.flat().filter(defined));
// Main layer is for showing the main visual representation such as marks. There
// may be multiple main layers for a view, each main layer correspond to one of marks.
// @todo Test DOM structure.
const T = selection
.selectAll(className(PLOT_CLASS_NAME))
.data([layout], () => key)
.join(
(enter) =>
enter
// Make this layer interactive, such as click and mousemove events.
.append('rect')
.style('zIndex', 0)
.style('fill', 'transparent')
.attr('className', PLOT_CLASS_NAME)
.call(updateBBox)
.call(updateLayers, Array.from(markState.keys()))
.call(applyClip, clip),
(update) =>
update
.call(updateLayers, Array.from(markState.keys()))
.call((selection) => {
return animationExtent
? animateBBox(selection, animationExtent)
: updateBBox(selection);
})
.call(applyClip, clip),
)
.transitions();
transitions.push(...T.flat());
// Render marks with corresponding data.
for (const [mark, state] of markState.entries()) {
const { data } = state;
const { key, class: cls, type } = mark;
const viewNode = selection.select(`#${key}`);
const shapeFunction = createMarkShapeFunction(mark, state, view, library);
const enterFunction = createEnterFunction(mark, state, view, library);
const updateFunction = createUpdateFunction(mark, state, view, library);
const exitFunction = createExitFunction(mark, state, view, library);
const facetElements = selectFacetElements(
selection,
viewNode,
cls,
'element',
);
const T = viewNode
.selectAll(className(ELEMENT_CLASS_NAME))
.selectFacetAll(facetElements)
.data(
data,
(d) => d.key,
(d) => d.groupKey,
)
.join(
(enter) =>
enter
.append(shapeFunction)
// Note!!! Only one className can be set.
// Using attribute as alternative for other classNames.
.attr('className', ELEMENT_CLASS_NAME)
.attr('markType', type)
.transition(function (data) {
return enterFunction(data, [this]);
}),
(update) =>
update.call((selection) => {
const parent = selection.parent();
const origin = useMemo<DisplayObject, [number, number]>((node) => {
const [x, y] = node.getBounds().min;
return [x, y];
});
update.transition(function (data, index) {
maybeFacetElement(this, parent, origin);
const node = shapeFunction(data, index);
const animation = updateFunction(data, [this], [node]);
if (animation === null) copyAttributes(this, node);
return animation;
});
}),
(exit) => {
return exit
.each(function () {
this.__removed__ = true;
})
.transition(function (data) {
return exitFunction(data, [this]);
})
.remove();
},
(merge) =>
merge
// Append elements to be merged.
.append(shapeFunction)
.attr('className', ELEMENT_CLASS_NAME)
.attr('markType', type)
.transition(function (data) {
// Remove merged elements after animation finishing.
const { __fromElements__: fromElements } = this;
const transition = updateFunction(data, fromElements, [this]);
const exit = new Selection(fromElements, null, this.parentNode);
exit.transition(transition).remove();
return transition;
}),
(split) =>
split
.transition(function (data) {
// Append splitted shapes.
const enter = new Selection([], this.__toData__, this.parentNode);
const toElements = enter
.append(shapeFunction)
.attr('className', ELEMENT_CLASS_NAME)
.attr('markType', type)
.nodes();
return updateFunction(data, [this], toElements);
})
// Remove elements to be splitted after animation finishing.
.remove(),
)
.transitions();
transitions.push(...T.flat());
}
// Plot label for this view.
plotLabel(view, selection, transitions, library);
}
/**
* Auto hide labels be specify label layout.
*/
function plotLabel(
view: G2ViewDescriptor,
selection: Selection,
transitions: GAnimation[],
library: G2Library,
) {
const [useLabelTransform] = useLibrary<
G2LabelTransformOptions,
LabelTransformComponent,
LabelTransform
>('labelTransform', library);
const { markState, labelTransform } = view;
const labelLayer = selection.select(className(LABEL_LAYER_CLASS_NAME)).node();
// A Map index shapeFunction by label.
const labelShapeFunction = new Map();
// A Map index options by label.
const labelDescriptor = new Map();
// Get all labels for this view.
const labels = Array.from(markState.entries()).flatMap(([mark, state]) => {
const { labels: labelOptions = [], key } = mark;
const shapeFunction = createLabelShapeFunction(mark, state, view, library);
const elements = selection
.select(`#${key}`)
.selectAll(className(ELEMENT_CLASS_NAME))
.nodes()
// Only select the valid element.
.filter((n) => !n.__removed__);
return labelOptions.flatMap((labelOption, i) => {
const { transform = [], ...options } = labelOption;
return elements.flatMap((e) => {
const L = getLabels(options, i, e);
L.forEach((l) => {
labelShapeFunction.set(l, shapeFunction);
labelDescriptor.set(l, labelOption);
});
return L;
});
});
});
// Render all labels.
const labelShapes = select(labelLayer)
.selectAll(className(LABEL_CLASS_NAME))
.data(labels, (d) => d.key)
.join(
(enter) =>
enter
.append((d) => labelShapeFunction.get(d)(d))
.attr('className', LABEL_CLASS_NAME),
(update) =>
update.each(function (d) {
// @todo Handle Label with different type.
const shapeFunction = labelShapeFunction.get(d);
const node = shapeFunction(d);
copyAttributes(this, node);
}),
(exit) => exit.remove(),
)
.nodes();
// Apply group-level transforms.
const labelGroups = group(labelShapes, (d) =>
labelDescriptor.get(d.__data__),
);
const { coordinate } = view;
for (const [label, shapes] of labelGroups) {
const { transform = [] } = label;
const transformFunction = composeLabelTransform(
transform.map(useLabelTransform),
);
transformFunction(shapes, coordinate);
}
// Apply view-level transform.
if (labelTransform) {
labelTransform(labelShapes, coordinate);
}
}
function composeLabelTransform(transform: LabelTransform[]): LabelTransform {
return (labels, coordinate) => {
for (const t of transform) {
labels = t(labels, coordinate);
}
return labels;
};
}
function getLabels(
label: Record<string, any>,
labelIndex: number,
element: G2Element,
): Record<string, any>[] {
const { seriesIndex: SI, seriesKey, points, key, index } = element.__data__;
const bounds = getLocalBounds(element);
if (!SI) {
return [
{
...label,
key: `${key}-${labelIndex}`,
bounds,
index,
points,
dependentElement: element,
},
];
}
const selector = normalizeLabelSelector(label);
const F = SI.map((index: number, i: number) => ({
...label,
key: `${seriesKey[i]}-${labelIndex}`,
bounds: [points[i]],
index,
points,
dependentElement: element,
}));
return selector ? selector(F) : F;
}
function filterValid([I, P, S]: [number[], Vector2[][], number[][]?]): [