@antv/g2 5.2.12 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/g2.lite.min.js +8 -8
  4. package/dist/g2.min.js +8 -8
  5. package/esm/animation/morphing.js +1 -2
  6. package/esm/animation/morphing.js.map +1 -1
  7. package/esm/interaction/elementSelect.d.ts +4 -2
  8. package/esm/interaction/elementSelect.js +50 -20
  9. package/esm/interaction/elementSelect.js.map +1 -1
  10. package/esm/interaction/event.js +1 -1
  11. package/esm/interaction/event.js.map +1 -1
  12. package/esm/interaction/tooltip.js +58 -10
  13. package/esm/interaction/tooltip.js.map +1 -1
  14. package/esm/interaction/utils.d.ts +12 -0
  15. package/esm/interaction/utils.js +48 -1
  16. package/esm/interaction/utils.js.map +1 -1
  17. package/esm/runtime/plot.js +9 -4
  18. package/esm/runtime/plot.js.map +1 -1
  19. package/esm/runtime/render.js +4 -2
  20. package/esm/runtime/render.js.map +1 -1
  21. package/esm/shape/point/color.js +2 -1
  22. package/esm/shape/point/color.js.map +1 -1
  23. package/esm/spec/interaction.d.ts +2 -0
  24. package/esm/spec/transform.d.ts +0 -1
  25. package/esm/transform/diffY.js +2 -5
  26. package/esm/transform/diffY.js.map +1 -1
  27. package/esm/transform/utils/helper.js +1 -0
  28. package/esm/transform/utils/helper.js.map +1 -1
  29. package/esm/utils/expr.d.ts +8 -0
  30. package/esm/utils/expr.js +51 -0
  31. package/esm/utils/expr.js.map +1 -0
  32. package/esm/utils/helper.d.ts +2 -1
  33. package/esm/utils/helper.js +4 -3
  34. package/esm/utils/helper.js.map +1 -1
  35. package/lib/animation/morphing.js +1 -2
  36. package/lib/animation/morphing.js.map +1 -1
  37. package/lib/interaction/elementSelect.d.ts +4 -2
  38. package/lib/interaction/elementSelect.js +49 -19
  39. package/lib/interaction/elementSelect.js.map +1 -1
  40. package/lib/interaction/event.js +1 -1
  41. package/lib/interaction/event.js.map +1 -1
  42. package/lib/interaction/tooltip.js +57 -9
  43. package/lib/interaction/tooltip.js.map +1 -1
  44. package/lib/interaction/utils.d.ts +12 -0
  45. package/lib/interaction/utils.js +49 -1
  46. package/lib/interaction/utils.js.map +1 -1
  47. package/lib/runtime/plot.js +9 -4
  48. package/lib/runtime/plot.js.map +1 -1
  49. package/lib/runtime/render.js +4 -2
  50. package/lib/runtime/render.js.map +1 -1
  51. package/lib/shape/point/color.js +2 -1
  52. package/lib/shape/point/color.js.map +1 -1
  53. package/lib/spec/interaction.d.ts +2 -0
  54. package/lib/spec/transform.d.ts +0 -1
  55. package/lib/transform/diffY.js +1 -4
  56. package/lib/transform/diffY.js.map +1 -1
  57. package/lib/transform/utils/helper.js +1 -0
  58. package/lib/transform/utils/helper.js.map +1 -1
  59. package/lib/utils/expr.d.ts +8 -0
  60. package/lib/utils/expr.js +55 -0
  61. package/lib/utils/expr.js.map +1 -0
  62. package/lib/utils/helper.d.ts +2 -1
  63. package/lib/utils/helper.js +4 -3
  64. package/lib/utils/helper.js.map +1 -1
  65. package/package.json +2 -1
  66. package/src/animation/morphing.ts +1 -2
  67. package/src/interaction/elementSelect.ts +70 -14
  68. package/src/interaction/event.ts +1 -1
  69. package/src/interaction/tooltip.ts +82 -8
  70. package/src/interaction/utils.ts +60 -1
  71. package/src/runtime/plot.ts +8 -3
  72. package/src/runtime/render.ts +4 -3
  73. package/src/shape/point/color.ts +2 -1
  74. package/src/spec/interaction.ts +2 -0
  75. package/src/spec/transform.ts +0 -1
  76. package/src/transform/diffY.ts +2 -6
  77. package/src/transform/utils/helper.ts +1 -0
  78. package/src/utils/expr.ts +70 -0
  79. package/src/utils/helper.ts +4 -3
@@ -13,6 +13,9 @@ import {
13
13
  offsetTransform,
14
14
  mergeState,
15
15
  selectElementByData,
16
+ createXKey,
17
+ createFindElementByEvent,
18
+ VALID_FIND_BY_X_MARKS,
16
19
  } from './utils';
17
20
 
18
21
  /**
@@ -24,6 +27,7 @@ export function elementSelect(
24
27
  elements: elementsof, // given the root of chart returns elements to be manipulated
25
28
  datum, // given each element returns the datum of it
26
29
  groupKey = (d) => d, // group elements by specified key
30
+ regionGroupKey = (d) => d, // how to group elements when click region
27
31
  link = false, // draw link or not
28
32
  single = false, // single select or not
29
33
  multipleSelectHotkey, // hotkey for multi-select mode
@@ -32,12 +36,22 @@ export function elementSelect(
32
36
  scale,
33
37
  emitter,
34
38
  state = {},
39
+ region = false,
35
40
  }: Record<string, any>,
36
41
  ) {
37
42
  const elements = elementsof(root);
38
43
  const elementSet = new Set(elements);
44
+ const findElement = createFindElementByEvent({
45
+ elementsof,
46
+ root,
47
+ coordinate,
48
+ scale,
49
+ });
39
50
  const keyGroup = group(elements, groupKey);
51
+ const regionGroup = group(elements, regionGroupKey);
52
+
40
53
  const valueof = createValueof(elements, datum);
54
+
41
55
  const [appendLink, removeLink] = renderLink({
42
56
  link,
43
57
  elements,
@@ -58,7 +72,7 @@ export function elementSelect(
58
72
  const elementStyle = deepMix(state, {
59
73
  selected: {
60
74
  ...(state.selected?.offset && {
61
- //Apply translate to mock slice out.
75
+ // Apply translate to mock slice out.
62
76
  transform: (...params) => {
63
77
  const value = state.selected.offset(...params);
64
78
  const [, i] = params;
@@ -82,14 +96,22 @@ export function elementSelect(
82
96
  return;
83
97
  };
84
98
 
85
- const singleSelect = (event, element, nativeEvent = true) => {
99
+ const singleSelect = ({
100
+ event,
101
+ element,
102
+ nativeEvent = true,
103
+ filter = (el) => true,
104
+ groupBy = groupKey,
105
+ groupMap = keyGroup,
106
+ }) => {
107
+ const filteredElements = elements.filter(filter);
86
108
  // Clear states if clicked selected element.
87
109
  if (hasState(element, 'selected')) clear();
88
110
  else {
89
- const k = groupKey(element);
90
- const group = keyGroup.get(k);
111
+ const k = groupBy(element);
112
+ const group = groupMap.get(k);
91
113
  const groupSet = new Set(group);
92
- for (const e of elements) {
114
+ for (const e of filteredElements) {
93
115
  if (groupSet.has(e)) setState(e, 'selected');
94
116
  else {
95
117
  setState(e, 'unselected');
@@ -111,13 +133,22 @@ export function elementSelect(
111
133
  }
112
134
  };
113
135
 
114
- const multipleSelect = (event, element, nativeEvent = true) => {
115
- const k = groupKey(element);
116
- const group = keyGroup.get(k);
136
+ const multipleSelect = ({
137
+ event,
138
+ element,
139
+ nativeEvent = true,
140
+ filter = (el) => true,
141
+ groupBy = groupKey,
142
+ groupMap = keyGroup,
143
+ }) => {
144
+ const k = groupBy(element);
145
+ const group = groupMap.get(k);
117
146
  const groupSet = new Set(group);
147
+ const filteredElements = elements.filter(filter);
148
+
118
149
  if (!hasState(element, 'selected')) {
119
150
  const hasSelectedGroup = group.some((e) => hasState(e, 'selected'));
120
- for (const e of elements) {
151
+ for (const e of filteredElements) {
121
152
  if (groupSet.has(e)) setState(e, 'selected');
122
153
  else if (!hasState(e, 'selected')) setState(e, 'unselected');
123
154
  }
@@ -151,11 +182,32 @@ export function elementSelect(
151
182
 
152
183
  const click = (event) => {
153
184
  const { target: element, nativeEvent = true } = event;
154
- // Click non-element shape, reset.
155
- // Such as the rest of content area(background).
156
- if (!elementSet.has(element)) return clear();
157
- if (!isMultiSelectMode) return singleSelect(event, element, nativeEvent);
158
- return multipleSelect(event, element, nativeEvent);
185
+
186
+ const select = !isMultiSelectMode ? singleSelect : multipleSelect;
187
+ let el = element;
188
+ const isClickElement = elementSet.has(element);
189
+
190
+ if (!region || isClickElement) {
191
+ // Click non-element shape, reset.
192
+ // Such as the rest of content area(background).
193
+ if (!isClickElement) return clear();
194
+ return select({ event, element: el, nativeEvent, groupBy: groupKey });
195
+ } else {
196
+ // Click background region area, select elements in the region.
197
+ // Get element at cursor.x position.
198
+ el = findElement(event);
199
+
200
+ if (!elementSet.has(el)) return clear();
201
+
202
+ return select({
203
+ event,
204
+ element: el,
205
+ nativeEvent,
206
+ filter: (el) => VALID_FIND_BY_X_MARKS.includes(el.markType),
207
+ groupBy: regionGroupKey,
208
+ groupMap: regionGroup,
209
+ });
210
+ }
159
211
  };
160
212
 
161
213
  // Handle keyboard events for multi-select mode
@@ -214,6 +266,7 @@ export function elementSelect(
214
266
 
215
267
  export function ElementSelect({
216
268
  createGroup,
269
+ createRegionGroup,
217
270
  background = false,
218
271
  link = false,
219
272
  ...rest
@@ -226,6 +279,9 @@ export function ElementSelect({
226
279
  elements: selectG2Elements,
227
280
  datum: createDatumof(view),
228
281
  groupKey: createGroup ? createGroup(view) : undefined,
282
+ regionGroupKey: createRegionGroup
283
+ ? createRegionGroup(view)
284
+ : createXKey(view),
229
285
  coordinate,
230
286
  scale,
231
287
  state: mergeState(options, [
@@ -50,7 +50,7 @@ function bubblesEvent(eventType, view, emitter, predicate = (event) => true) {
50
50
  nativeEvent: true,
51
51
  };
52
52
  if (elementType === 'element') {
53
- e1['data'] = { data: dataOf(root) };
53
+ e1['data'] = { data: dataOf(root, view) };
54
54
  emitter.emit(`element:${eventType}`, e1);
55
55
  emitter.emit(`${markType}:${eventType}`, e1);
56
56
  } else if (elementType === 'label') {
@@ -1,5 +1,12 @@
1
1
  import { Circle, DisplayObject, IElement, Line } from '@antv/g';
2
- import { sort, group, mean, bisector, minIndex } from '@antv/vendor/d3-array';
2
+ import {
3
+ sort,
4
+ group,
5
+ mean,
6
+ bisector,
7
+ minIndex,
8
+ bisect,
9
+ } from '@antv/vendor/d3-array';
3
10
  import { deepMix, lowerFirst, throttle } from '@antv/util';
4
11
  import { Tooltip as TooltipComponent } from '@antv/component';
5
12
  import { defined, groupNameOf, subObject, dataOf } from '../utils/helper';
@@ -234,7 +241,11 @@ function groupItems(
234
241
  ).filter(defined);
235
242
  const newItems = data
236
243
  .flatMap((datum, i) => {
237
- const element = elements[i];
244
+ const element = elements.find(
245
+ (element) =>
246
+ element.__data__.seriesKey?.includes(datum.key) ||
247
+ element.__data__.key === datum.key,
248
+ );
238
249
  const { items = [], title } = datum;
239
250
  const definedItems = items.filter(defined);
240
251
 
@@ -479,6 +490,8 @@ function updateMarker(root, { data, style, theme }) {
479
490
  r: 4,
480
491
  stroke,
481
492
  lineWidth: 2,
493
+ // Prevents blocking clicks on elements behind.
494
+ pointerEvents: 'none',
482
495
  ...style,
483
496
  },
484
497
  });
@@ -630,6 +643,7 @@ export function seriesTooltip(
630
643
  );
631
644
 
632
645
  const { x: scaleX } = scale;
646
+ const stepWidth = scaleX?.getStep?.() ?? 0;
633
647
 
634
648
  // Apply offset for band scale x.
635
649
  const offsetX = scaleX?.getBandWidth ? scaleX.getBandWidth() / 2 : 0;
@@ -640,6 +654,9 @@ export function seriesTooltip(
640
654
  };
641
655
 
642
656
  const indexByFocus = (event, focus, I, X) => {
657
+ const isOutRange = (x, min, max) => x < min || x > max;
658
+ const shouldSkip = (closest, isRangeViolation, isInvalid) =>
659
+ !closest && isRangeViolation && isInvalid;
643
660
  // _x is from emit event, to find the right element.
644
661
  const { _x } = event;
645
662
  const finalX = _x !== undefined ? scaleX.map(_x) : abstractX(focus);
@@ -650,20 +667,63 @@ export function seriesTooltip(
650
667
 
651
668
  // If closest is true, always find at least one element.
652
669
  // Otherwise, skip element out of plot area.
653
- if (!closest && (finalX < minX || finalX > maxX) && !isOnlyOneElement)
670
+ if (shouldSkip(closest, isOutRange(finalX, minX, maxX), !isOnlyOneElement))
654
671
  return null;
672
+
655
673
  const search = bisector((i) => X[+i]).center;
656
674
  const i = search(I, finalX);
675
+ if (isOnlyOneElement) {
676
+ // if is only one element, find the closest x to focusX
677
+ const sortedDomain: number[] = scaleX.adjustedRange;
678
+ if (
679
+ // consider oneElementLine, if only one element of one XDomain, must return one element, related test case: tooltip/one-element-line
680
+ // else if multi elements, determine whether it is between the minimum scope and the maximum scope
681
+ shouldSkip(
682
+ closest,
683
+ isOutRange(
684
+ finalX,
685
+ sortedDomain[0],
686
+ sortedDomain[sortedDomain.length - 1],
687
+ ),
688
+ !(sortedDomain.length === 1),
689
+ )
690
+ )
691
+ return null;
692
+
693
+ return I[i];
694
+ }
657
695
  return I[i];
658
696
  };
659
697
 
698
+ // get x domain by point
699
+ const getDomainXByPoint = (point) => {
700
+ const [pointX] = coordinate.invert(point);
701
+ const rangeIndexMap = scaleX.rangeIndexMap;
702
+ const domainXs = Array.from(rangeIndexMap.keys()).map(
703
+ (d: number) => d - (stepWidth - scaleX.getBandWidth()) / 2,
704
+ );
705
+ const index = bisect(domainXs as number[], pointX);
706
+ return scaleX.sortedDomain[index - 1];
707
+ };
708
+
660
709
  const elementsByFocus = isBar
661
710
  ? (focus, elements) => {
662
711
  const search = bisector(xof).center;
663
- const i = search(elements, abstractX(focus));
664
- const find = elements[i];
665
- const groups = group(elements, xof);
666
- const selected = groups.get(xof(find));
712
+ const pointX = abstractX(focus);
713
+ const parentOf = (d) => d.parentNode;
714
+ const elementGroups = group(elements, parentOf);
715
+ const selected = [];
716
+
717
+ const domainX = getDomainXByPoint(focus);
718
+ elementGroups.forEach((elements) => {
719
+ const i = search(elements, pointX);
720
+ const find = elements[i];
721
+
722
+ if (domainX === (find as any).__data__.title) {
723
+ selected.push(find);
724
+ }
725
+ });
726
+
667
727
  return selected;
668
728
  }
669
729
  : (focus, elements) => {
@@ -972,6 +1032,7 @@ export function tooltip(
972
1032
  const scaleX = scale.x;
973
1033
  const scaleSeries = scale.series;
974
1034
  const bandWidth = scaleX?.getBandWidth?.() ?? 0;
1035
+ const stepWidth = scaleX?.getStep?.() ?? 0;
975
1036
  const xof = scaleSeries
976
1037
  ? (d) => {
977
1038
  const seriesCount = Math.round(1 / scaleSeries.valueBandWidth);
@@ -1003,6 +1064,19 @@ export function tooltip(
1003
1064
  const i = search(elements, abstractX);
1004
1065
  const target = elements[i];
1005
1066
 
1067
+ // Handle the case where stepWidth is negative.
1068
+ const isStepWidthPositive = stepWidth > 0;
1069
+ const targetLeftBoundary = isStepWidthPositive
1070
+ ? xof(target) - stepWidth / 2
1071
+ : xof(target) + stepWidth / 2;
1072
+ const targetRightBoundary = isStepWidthPositive
1073
+ ? xof(target) + stepWidth / 2
1074
+ : xof(target) - stepWidth / 2;
1075
+
1076
+ if (abstractX < targetLeftBoundary || abstractX > targetRightBoundary) {
1077
+ return;
1078
+ }
1079
+
1006
1080
  if (!shared) {
1007
1081
  // For grouped bar chart without shared options.
1008
1082
  const isGrouped = elements.find(
@@ -1068,7 +1142,7 @@ export function tooltip(
1068
1142
  nativeEvent: true,
1069
1143
  data: {
1070
1144
  ...data,
1071
- data: dataOf(element),
1145
+ data: dataOf(element, view),
1072
1146
  },
1073
1147
  });
1074
1148
  },
@@ -1,6 +1,6 @@
1
1
  import { DisplayObject, Path, AABB } from '@antv/g';
2
2
  import { path as d3Path } from '@antv/vendor/d3-path';
3
- import { sort } from '@antv/vendor/d3-array';
3
+ import { sort, bisector } from '@antv/vendor/d3-array';
4
4
  import { Vector2 } from '@antv/coord';
5
5
  import { filter } from '@antv/util';
6
6
  import type { PathArray } from '@antv/util';
@@ -532,3 +532,62 @@ export function maybeRoot(node, rootOf) {
532
532
  while (root && !rootOf(root)) root = root.parent;
533
533
  return root;
534
534
  }
535
+
536
+ export const VALID_FIND_BY_X_MARKS = ['interval', 'point', 'density'];
537
+ /**
538
+ * @description Create function that can find element by event.
539
+ * @returns Element find function.
540
+ */
541
+ export function createFindElementByEvent({
542
+ elementsof,
543
+ root,
544
+ coordinate,
545
+ scale,
546
+ validFindByXMarks = VALID_FIND_BY_X_MARKS,
547
+ }) {
548
+ let elements = elementsof(root);
549
+ const getValidFindByXMarks = (d) => validFindByXMarks.includes(d.markType);
550
+ const hasValidFindByXMarks = elements.find(getValidFindByXMarks);
551
+
552
+ // Try to find element by x position.
553
+ if (hasValidFindByXMarks) {
554
+ elements = elements.filter(getValidFindByXMarks);
555
+
556
+ const scaleX = scale.x;
557
+ const scaleSeries = scale.series;
558
+ const bandWidth = scaleX?.getBandWidth?.() ?? 0;
559
+ const xof = scaleSeries
560
+ ? (d) => {
561
+ const seriesCount = Math.round(1 / scaleSeries.valueBandWidth);
562
+ return (
563
+ d.__data__.x +
564
+ d.__data__.series * bandWidth +
565
+ bandWidth / (seriesCount * 2)
566
+ );
567
+ }
568
+ : (d) => d.__data__.x + bandWidth / 2;
569
+
570
+ // Sort for bisector search.
571
+ elements.sort((a, b) => xof(a) - xof(b));
572
+
573
+ return (event) => {
574
+ const mouse = mousePosition(root, event);
575
+ if (!mouse) return;
576
+ const [abstractX] = coordinate.invert(mouse);
577
+ const search = bisector(xof).center;
578
+ const i = search(elements, abstractX);
579
+ const target = elements[i];
580
+
581
+ return target;
582
+ };
583
+ }
584
+
585
+ // If there is no valid element find by x, just return the target element.
586
+ return (event) => {
587
+ const { target } = event;
588
+ return maybeRoot(target, (node) => {
589
+ if (!node.classList) return false;
590
+ return node.classList.includes('element');
591
+ });
592
+ };
593
+ }
@@ -1078,7 +1078,7 @@ async function plotView(
1078
1078
  maybeFacetElement(element, parent, origin);
1079
1079
  const node = shapeFunction(data, index);
1080
1080
  const animation = updateFunction(data, [element], [node]);
1081
- if (animation !== null) return animation;
1081
+ if (animation?.length) return animation;
1082
1082
  if (
1083
1083
  element.nodeName === node.nodeName &&
1084
1084
  node.nodeName !== 'g'
@@ -1631,8 +1631,13 @@ function createAnimationFunction(
1631
1631
  const animateFunction = useAnimation(options, context);
1632
1632
  const value = { delay, duration, easing };
1633
1633
  const A = animateFunction(from, to, deepMix(defaultEffectTiming, value));
1634
- if (!Array.isArray(A)) return [A];
1635
- return A;
1634
+ let an: GAnimation[] = [];
1635
+ if (!Array.isArray(A)) {
1636
+ an = [A];
1637
+ } else {
1638
+ an = A;
1639
+ }
1640
+ return an.filter(Boolean);
1636
1641
  };
1637
1642
  }
1638
1643
 
@@ -6,11 +6,11 @@ import EventEmitter from '@antv/event-emitter';
6
6
  import { select } from '../utils/selection';
7
7
  import { ChartEvent } from '../utils/event';
8
8
  import { error } from '../utils/helper';
9
+ import { parseOptionsExpr } from '../utils/expr';
9
10
  import { G2Context, G2ViewTree } from './types/options';
10
11
  import { plot } from './plot';
11
12
  import { VIEW_CLASS_NAME } from './constant';
12
13
  import { preprocessOption } from './option-preprocess';
13
-
14
14
  /**
15
15
  * Infer key for each node of view tree.
16
16
  * Each key should be unique in the entire view tree.
@@ -70,10 +70,11 @@ export function render<T extends G2ViewTree = G2ViewTree>(
70
70
  throw e;
71
71
  },
72
72
  ): HTMLElement {
73
+ const afterParsedOptions = parseOptionsExpr(options);
73
74
  // Initialize the context if it is not provided.
74
- const { width = 640, height = 480, depth = 0 } = options;
75
+ const { width = 640, height = 480, depth = 0 } = afterParsedOptions;
75
76
  // Preprocessing here, such as syntactic sugar.
76
- const preprocessedOption = preprocessOption(options);
77
+ const preprocessedOption = preprocessOption(afterParsedOptions);
77
78
  const keyed = inferKeys(preprocessedOption);
78
79
  const {
79
80
  canvas = Canvas(width, height),
@@ -3,6 +3,7 @@ import { ShapeComponent as SC } from '../../runtime';
3
3
  import { isFisheye } from '../../utils/coordinate';
4
4
  import { Symbols } from '../../utils/marker';
5
5
  import { select } from '../../utils/selection';
6
+ import { camelCase } from '../../utils/string';
6
7
  import { applyStyle, getOrigin, toOpacityKey } from '../utils';
7
8
 
8
9
  export type ColorOptions = {
@@ -36,7 +37,7 @@ export function getRadius(
36
37
  export const Color: SC<ColorOptions> = (options, context) => {
37
38
  // Render border only when colorAttribute is stroke.
38
39
  const { colorAttribute, symbol, mode = 'auto', ...style } = options;
39
- const path = Symbols.get(symbol) || Symbols.get('point');
40
+ const path = Symbols.get(camelCase(symbol)) || Symbols.get('point');
40
41
  const { coordinate, document } = context;
41
42
  return (points, value, defaults) => {
42
43
  const { lineWidth, color: defaultColor } = defaults;
@@ -108,6 +108,7 @@ export type ElementSelectInteraction = {
108
108
  background?: boolean;
109
109
  offset?: number;
110
110
  multipleSelectHotkey?: string;
111
+ region?: boolean;
111
112
  } & Record<`${'link' | 'background'}${any}`, any>;
112
113
 
113
114
  export type ElementSelectByColorInteraction = {
@@ -119,6 +120,7 @@ export type ElementSelectByColorInteraction = {
119
120
 
120
121
  export type ElementSelectByXInteraction = {
121
122
  type?: 'elementSelectByX';
123
+ region?: boolean;
122
124
  single?: boolean;
123
125
  background?: boolean;
124
126
  offset?: number;
@@ -134,7 +134,6 @@ export type SymmetryYTransform = {
134
134
  export type DiffYTransform = {
135
135
  type?: 'diffY';
136
136
  groupBy?: string | string[];
137
- series?: boolean;
138
137
  };
139
138
 
140
139
  export type Selector =
@@ -1,7 +1,7 @@
1
1
  import { deepMix } from '@antv/util';
2
2
  import { TransformComponent as TC } from '../runtime';
3
3
  import { DiffYTransform } from '../spec';
4
- import { column, columnOf, maybeColumnOf } from './utils/helper';
4
+ import { column, columnOf } from './utils/helper';
5
5
  import { createGroups } from './utils/order';
6
6
 
7
7
  export type DiffYOptions = Omit<DiffYTransform, 'type'>;
@@ -11,16 +11,12 @@ export type DiffYOptions = Omit<DiffYTransform, 'type'>;
11
11
  * Keep y unchanged, set y1 = max(otherY), if y1 > y, remove the data.
12
12
  */
13
13
  export const DiffY: TC<DiffYOptions> = (options = {}) => {
14
- const { groupBy = 'x', series = true } = options;
14
+ const { groupBy = 'x' } = options;
15
15
  return (I, mark) => {
16
16
  const { encode } = mark;
17
17
  const [Y] = columnOf(encode, 'y');
18
18
  const [_, fy1] = columnOf(encode, 'y1');
19
19
 
20
- const [S] = series
21
- ? maybeColumnOf(encode, 'series', 'color')
22
- : columnOf(encode, 'color');
23
-
24
20
  // Create groups and apply specified order for each group.
25
21
  const groups = createGroups(groupBy, I, mark);
26
22
 
@@ -37,6 +37,7 @@ export function maybeColumnOf(
37
37
  encode,
38
38
  ...K: (string | Primitive[])[]
39
39
  ): [Primitive[], string] {
40
+ console.log('maybeColumnOf', encode, K);
40
41
  for (const key of K) {
41
42
  if (typeof key === 'string') {
42
43
  const [KV, fv] = columnOf(encode, key);
@@ -0,0 +1,70 @@
1
+ import { compile } from '@antv/expr';
2
+ import { mapValues } from '@antv/util';
3
+ import { lru } from './lru';
4
+
5
+ // Whitelist of properties that can contain expressions.
6
+ export const EXPR_WHITE_LIST = ['style', 'encode', 'labels', 'children'];
7
+
8
+ /**
9
+ * Compiles an expression string into a function.
10
+ * @param expr Expression string to compile.
11
+ * @returns Compiled function or original string if empty.
12
+ */
13
+ const compileExpression = lru(
14
+ (expr: string): (() => any) | string => {
15
+ const evaluator = compile(expr);
16
+
17
+ return (...args) => {
18
+ const paramNames = Array.from({ length: args.length }, (_, i) =>
19
+ String.fromCharCode(97 + i),
20
+ );
21
+
22
+ const namedParams = Object.fromEntries(
23
+ args.map((value, index) => [paramNames[index], value]),
24
+ );
25
+
26
+ // global is used to overview what can i get in props.
27
+ return evaluator({
28
+ ...namedParams,
29
+ global: { ...namedParams },
30
+ });
31
+ };
32
+ },
33
+ (expr) => expr,
34
+ 128,
35
+ );
36
+
37
+ /**
38
+ * Processes options object to convert expressions to functions.
39
+ * @param options Options object to process.
40
+ * @param isSpecRoot Whether the options is the root of the spec.
41
+ * @returns Processed options object with expressions converted to functions.
42
+ */
43
+ export function parseOptionsExpr(options: any, isSpecRoot = true): any {
44
+ if (Array.isArray(options)) {
45
+ return options.map((_, i) => parseOptionsExpr(options[i], isSpecRoot));
46
+ }
47
+
48
+ if (typeof options === 'object' && options) {
49
+ return mapValues(options, (value, key) => {
50
+ // if options is root and the key is in the white list, parse the expression.
51
+ if (isSpecRoot && EXPR_WHITE_LIST.includes(key)) {
52
+ return parseOptionsExpr(value, key === 'children');
53
+ }
54
+ if (!isSpecRoot) {
55
+ return parseOptionsExpr(value, false);
56
+ }
57
+ return value;
58
+ });
59
+ }
60
+
61
+ // if options is a string and is a valid expression.
62
+ if (typeof options === 'string') {
63
+ const trimmed = options.trim();
64
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
65
+ return compileExpression(trimmed.slice(1, -1));
66
+ }
67
+ }
68
+
69
+ return options;
70
+ }
@@ -20,13 +20,14 @@ export function getViewFromElement(element: G2Element) {
20
20
  /**
21
21
  * @description Get element's original data.
22
22
  * @param elemenet G2 element.
23
+ * @param elemenet View data, if not provided, will get from element's ancestor view.
23
24
  * @returns The original data of the element.
24
25
  */
25
- export function dataOf(element: G2Element) {
26
- const view = getViewFromElement(element);
26
+ export function dataOf(element: G2Element, viewData?: any) {
27
+ const view = viewData ?? getViewFromElement(element).__data__;
27
28
  const datum = element.__data__;
28
29
  const { markKey, index, seriesIndex } = datum;
29
- const { markState } = view.__data__;
30
+ const { markState } = view;
30
31
  const selectedMark: any = Array.from(markState.keys()).find(
31
32
  (mark) => (mark as any).key === markKey,
32
33
  );