Skip to content

Commit 6380350

Browse files
fix: pass labels to label callbacks (#7268)
* fix: pass labels to label callbacks * test: extract canvas setup to beforeEach
1 parent 4730d52 commit 6380350

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { vi } from 'vitest';
2+
import { Band } from '@antv/scale';
3+
import { Canvas } from '@antv/g';
4+
import { computeLabelsBBox } from '../../../src/runtime/component';
5+
import { createNodeGCanvas } from '../../integration/utils/createNodeGCanvas';
6+
7+
describe('computeLabelsBBox', () => {
8+
let canvas: Canvas;
9+
10+
beforeEach(async () => {
11+
canvas = createNodeGCanvas(640, 480);
12+
await canvas.ready;
13+
});
14+
15+
it('should pass labels array to label callbacks', async () => {
16+
const labels = ['A', 'B', 'C'];
17+
18+
const scale = new Band();
19+
scale.update({ domain: labels, range: [0, 1] });
20+
21+
const labelFontSize = vi.fn(
22+
(_datum: string, _index: number, _data: string[]) => 12,
23+
);
24+
25+
const component = {
26+
label: true,
27+
labelFontSize,
28+
};
29+
30+
computeLabelsBBox(component, scale);
31+
32+
expect(labelFontSize).toHaveBeenCalledTimes(3);
33+
expect(labelFontSize.mock.calls).toEqual([
34+
['A', 0, ['A', 'B', 'C']],
35+
['B', 1, ['A', 'B', 'C']],
36+
['C', 2, ['A', 'B', 'C']],
37+
]);
38+
39+
const dataArgs = labelFontSize.mock.calls.map(([, , data]) => data);
40+
expect(new Set(dataArgs).size).toBe(1);
41+
expect(dataArgs[0]).toEqual(labels);
42+
});
43+
44+
it('should pass labels array to keyed callbacks', async () => {
45+
const labels = ['A', 'B', 'C'];
46+
const scale = new Band();
47+
scale.update({ domain: labels, range: [0, 1] });
48+
49+
const itemLabelFontSize = vi.fn(
50+
(_datum: string, _index: number, data: string[]) =>
51+
data.length ? 12 : 0,
52+
);
53+
54+
const component = {
55+
label: true,
56+
itemLabelFontSize,
57+
};
58+
59+
computeLabelsBBox(component, scale, 'itemLabel');
60+
61+
expect(itemLabelFontSize).toHaveBeenCalledTimes(3);
62+
expect(itemLabelFontSize.mock.calls).toEqual([
63+
['A', 0, ['A', 'B', 'C']],
64+
['B', 1, ['A', 'B', 'C']],
65+
['C', 2, ['A', 'B', 'C']],
66+
]);
67+
});
68+
});

src/runtime/component.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,7 @@ export function computeLabelsBBox(
10681068
Object.fromEntries(
10691069
Object.entries(labelStyle).map(([key, value]) => [
10701070
key,
1071-
typeof value === 'function' ? value(d, i) : value,
1071+
typeof value === 'function' ? value(d, i, labels) : value,
10721072
]),
10731073
),
10741074
);

0 commit comments

Comments
 (0)