diff --git a/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-hides-overlapping-point-labels-by-default-1-chromium-linux.png b/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-hides-overlapping-point-labels-by-default-1-chromium-linux.png
new file mode 100644
index 00000000..add3e947
Binary files /dev/null and b/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-hides-overlapping-point-labels-by-default-1-chromium-linux.png differ
diff --git a/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-renders-normalized-line-labels-at-plot-boundaries-1-chromium-linux.png b/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-renders-normalized-line-labels-at-plot-boundaries-1-chromium-linux.png
new file mode 100644
index 00000000..b1bb29bf
Binary files /dev/null and b/src/plugins/yagr/__screenshots__/labels.visual.test.tsx-screenshots/Yagr-canvas-labels-integration-renders-normalized-line-labels-at-plot-boundaries-1-chromium-linux.png differ
diff --git a/src/plugins/yagr/__stories__/Yagr.stories.tsx b/src/plugins/yagr/__stories__/Yagr.stories.tsx
index 45eff450..ec1d4988 100644
--- a/src/plugins/yagr/__stories__/Yagr.stories.tsx
+++ b/src/plugins/yagr/__stories__/Yagr.stories.tsx
@@ -1,7 +1,7 @@
import React, {useEffect, useState} from 'react';
import {dateTime} from '@gravity-ui/date-utils';
-import {Button} from '@gravity-ui/uikit';
+import {Button, Flex} from '@gravity-ui/uikit';
import {placement} from '@gravity-ui/yagr';
import type {Meta, StoryObj} from '@storybook/react';
@@ -9,7 +9,9 @@ import {CustomTooltipProps, TooltipHandlerData, YagrPlugin} from '../';
import {ChartKit} from '../../../components/ChartKit';
import {settings} from '../../../libs';
import type {ChartKitRef} from '../../../types';
+import type {YagrWidgetData} from '../types';
+import {LABELED_DATA} from './mocks/labels';
import {getNewConfig, line10, line10WithGrafanaStyle} from './mocks/line10';
import '@gravity-ui/yagr/index.css';
@@ -159,3 +161,38 @@ export const Area: Story = {
);
},
};
+
+export const DataLabels: Story = {
+ render: () => {
+ const [enabled, setEnabled] = React.useState(true);
+ const [padding, setPadding] = React.useState(5);
+ settings.set({plugins: [YagrPlugin]});
+
+ const data: YagrWidgetData = {
+ ...LABELED_DATA,
+ data: {
+ ...LABELED_DATA.data,
+ graphs: LABELED_DATA.data.graphs.map((graph) => ({
+ ...graph,
+ dataLabels: {enabled, padding},
+ })),
+ },
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+ );
+ },
+};
diff --git a/src/plugins/yagr/__stories__/mocks/labels.ts b/src/plugins/yagr/__stories__/mocks/labels.ts
new file mode 100644
index 00000000..21022831
--- /dev/null
+++ b/src/plugins/yagr/__stories__/mocks/labels.ts
@@ -0,0 +1,16 @@
+import type {YagrWidgetData} from '../../types';
+
+export const LABELED_DATA: YagrWidgetData = {
+ data: {
+ timeline: [Date.UTC(2026, 0, 1), Date.UTC(2026, 0, 2), Date.UTC(2026, 0, 3)],
+ graphs: [
+ {
+ id: 'revenue',
+ name: 'Revenue',
+ type: 'line',
+ _data: [{value: 10, label: 'Plan'}, {value: 20}, {value: 15, label: ''}],
+ },
+ ],
+ },
+ libraryConfig: {scales: {y: {min: 0, max: 40}}},
+};
diff --git a/src/plugins/yagr/__tests__/data-labels.test.ts b/src/plugins/yagr/__tests__/data-labels.test.ts
new file mode 100644
index 00000000..53a47d7e
--- /dev/null
+++ b/src/plugins/yagr/__tests__/data-labels.test.ts
@@ -0,0 +1,308 @@
+import {YagrDataLabelsPlugin as createDataLabelsPlugin} from '../plugins/YagrDataLabelsPlugin';
+import {shapeYagrConfig} from '../renderer/utils';
+import type {Yagr, YagrGraph, YagrWidgetData} from '../types';
+
+function createChartMock(
+ graphs: YagrGraph[] = [
+ {id: 'a', _data: [{value: 20, label: 'Plan'}], dataLabels: {enabled: true}},
+ ],
+ libraryConfig: YagrWidgetData['libraryConfig'] = {},
+) {
+ const config = shapeYagrConfig({data: {timeline: [1], graphs}, libraryConfig, theme: 'light'});
+ const ctx = {
+ canvas: {width: 800},
+ font: '',
+ fillStyle: '',
+ textAlign: '',
+ textBaseline: '',
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ rect: vi.fn(),
+ clip: vi.fn(),
+ fillText: vi.fn(),
+ measureText: vi.fn(() => ({
+ width: 40,
+ actualBoundingBoxAscent: 18,
+ actualBoundingBoxDescent: 2,
+ })),
+ };
+ const u = {
+ ctx,
+ width: 400,
+ bbox: {left: 20, top: 20, width: 760, height: 480},
+ series: [{}, ...config.series.map((series) => ({id: series.id, show: true, scale: 'y'}))],
+ data: [[1], ...graphs.map(() => [30])],
+ valToPos: vi.fn((value, scale) => (scale === 'x' ? value * 200 : value * 2)),
+ } as unknown as Yagr['uplot'];
+ const chart = {
+ config,
+ root: {},
+ utils: {colors: {parse: vi.fn(() => 'rgb(1, 2, 3)')}},
+ } as unknown as Yagr;
+ const hooks = createDataLabelsPlugin(chart).uplot.hooks.draw;
+ const hook = Array.isArray(hooks) ? hooks[0] : hooks;
+ if (typeof hook !== 'function') throw new Error('Missing draw hook');
+
+ return {ctx, u, chart, draw: () => hook(u)};
+}
+
+describe('YagrDataLabelsPlugin', () => {
+ beforeEach(() => vi.stubGlobal('getComputedStyle', () => ({fontFamily: 'Arial'})));
+ afterEach(() => vi.unstubAllGlobals());
+
+ const pixelRatioCases = [
+ {ratio: 1, font: 'bold 11px Arial', labelY: 55},
+ {ratio: 1.5, font: 'bold 16.5px Arial', labelY: 52.5},
+ {ratio: 2, font: 'bold 22px Arial', labelY: 50},
+ ];
+
+ test.each(pixelRatioCases)(
+ 'draws source text at prepared coordinates with pixel ratio $ratio',
+ ({ratio, font, labelY}) => {
+ const {ctx, u, draw} = createChartMock();
+ ctx.canvas.width = 400 * ratio;
+ draw();
+
+ expect(ctx.fillText).toHaveBeenCalledWith('Plan', 200, labelY);
+ expect(u.valToPos).toHaveBeenCalledWith(30, 'y', true);
+ expect(ctx.font).toBe(font);
+ expect(ctx.fillStyle).toBe('rgb(1, 2, 3)');
+ },
+ );
+
+ const disabledCases: YagrGraph[] = [
+ {_data: [{value: 20, label: 'Plan'}]},
+ {_data: [{value: 20, label: 'Plan'}], dataLabels: {enabled: false}},
+ {data: [20], type: 'column', dataLabels: {enabled: true}},
+ {data: [20], type: 'area', dataLabels: {enabled: true}},
+ {data: [20], type: 'dots', dataLabels: {enabled: true}},
+ ];
+ test.each(disabledCases)('ignores disabled labels and non-line types: %j', (graph) => {
+ const {ctx, draw} = createChartMock([{...graph, id: 'a'}]);
+ draw();
+ expect(ctx.fillText).not.toHaveBeenCalled();
+ });
+
+ test('resolves the common type with a per-series override', () => {
+ const graph: YagrGraph = {id: 'a', data: [20], dataLabels: {enabled: true}};
+ const hidden = createChartMock([graph], {chart: {series: {type: 'column'}}});
+ hidden.draw();
+ expect(hidden.ctx.fillText).not.toHaveBeenCalled();
+
+ const visible = createChartMock([{...graph, type: 'line'}], {
+ chart: {series: {type: 'column'}},
+ });
+ visible.draw();
+ expect(visible.ctx.fillText).toHaveBeenCalledWith('20', 200, 50);
+ });
+
+ test('uses the effective uPlot series type', () => {
+ const {u, ctx, draw} = createChartMock();
+ u.series[1].type = 'column';
+ draw();
+ expect(ctx.fillText).not.toHaveBeenCalled();
+ });
+
+ test('handles default text, empty text, null values and zero', () => {
+ const graph: YagrGraph = {
+ id: 'a',
+ _data: [
+ {value: 10, label: 'Plan'},
+ {value: 20},
+ {value: 15, label: ''},
+ {value: null, label: 'Missing'},
+ {value: 0, label: null},
+ ],
+ dataLabels: {enabled: true},
+ };
+ const {u, ctx, draw} = createChartMock([graph]);
+ u.data[0] = [1, 1.5, 2, 2.5, 3];
+ u.data[1] = [30, 30, 30, 30, 30];
+ draw();
+ expect(ctx.fillText.mock.calls.map(([text]) => text)).toEqual(['Plan', '20', '0']);
+ });
+
+ const pointOverlapCases = [
+ {allowOverlap: undefined, expected: ['Upper', 'Left']},
+ {allowOverlap: true, expected: ['Lower', 'Right', 'Upper', 'Left']},
+ ];
+
+ test.each(pointOverlapCases)(
+ 'filters labels by y then x unless overlap is allowed: $allowOverlap',
+ ({allowOverlap, expected}) => {
+ const graph: YagrGraph = {
+ id: 'a',
+ _data: [
+ {value: 1, label: 'Lower'},
+ {value: 1, label: 'Right'},
+ {value: 1, label: 'Upper'},
+ {value: 1, label: 'Left'},
+ ],
+ dataLabels: {enabled: true, allowOverlap},
+ };
+ const {ctx, u, draw} = createChartMock([graph]);
+ u.data[0] = [200, 220, 200, 200];
+ u.data[1] = [212, 200, 180, 200];
+ vi.mocked(u.valToPos).mockImplementation((value) => value);
+
+ draw();
+ expect(ctx.fillText.mock.calls.map(([text]) => text)).toEqual(expected);
+
+ ctx.fillText.mockClear();
+ draw();
+ expect(ctx.fillText.mock.calls.map(([text]) => text)).toEqual(expected);
+ },
+ );
+
+ const overlappingSeries: YagrGraph[] = [
+ {
+ id: 'first',
+ _data: [{value: 1, label: 'First'}, {value: null}, {value: null}],
+ },
+ {
+ id: 'middle',
+ _data: [{value: null}, {value: 1, label: 'Middle'}, {value: null}],
+ },
+ {
+ id: 'last',
+ _data: [{value: null}, {value: null}, {value: 1, label: 'Last'}],
+ },
+ ];
+ const seriesOverlapCases = [
+ {allowOverlap: undefined, expected: ['Last', 'First']},
+ {allowOverlap: true, expected: ['Last', 'Middle']},
+ ];
+
+ test.each(seriesOverlapCases)(
+ 'prioritizes later series and keeps allowed overlaps as obstacles: $allowOverlap',
+ ({allowOverlap, expected}) => {
+ const graphs = overlappingSeries.map((graph) => ({
+ ...graph,
+ dataLabels: {
+ enabled: true,
+ allowOverlap: graph.id === 'middle' ? allowOverlap : undefined,
+ },
+ }));
+ const {ctx, u, draw} = createChartMock(graphs);
+ u.data[0] = [1, 1.1, 1.2];
+ u.data[1] = [30, null, null];
+ u.data[2] = [null, 30, null];
+ u.data[3] = [null, null, 30];
+ draw();
+ expect(ctx.fillText.mock.calls.map(([text]) => text)).toEqual(expected);
+ },
+ );
+
+ test('keeps padding above the actual text bounds with a negative descent', () => {
+ const {ctx, u, draw} = createChartMock();
+ ctx.measureText.mockReturnValue({
+ width: 40,
+ actualBoundingBoxAscent: 20,
+ actualBoundingBoxDescent: -4,
+ });
+ vi.mocked(u.valToPos).mockImplementation((_value, scale) =>
+ scale === 'x' ? 200 : u.bbox.top,
+ );
+ draw();
+ expect(ctx.fillText).toHaveBeenCalledWith('Plan', 200, 50);
+ });
+
+ test('reads replacement config by id on every draw, including padding zero', () => {
+ const {ctx, draw, chart} = createChartMock();
+ draw();
+ const replacement = shapeYagrConfig({
+ data: {
+ timeline: [1],
+ graphs: [
+ {
+ id: 'a',
+ _data: [{value: 4, label: 'Updated'}],
+ dataLabels: {enabled: true, padding: 0},
+ },
+ ],
+ },
+ libraryConfig: {},
+ theme: 'light',
+ });
+ chart.config.series = replacement.series;
+ ctx.fillText.mockClear();
+ draw();
+ expect(ctx.fillText).toHaveBeenCalledWith('Updated', 200, 60);
+ });
+
+ test('resolves series by id with independent padding when uPlot order differs', () => {
+ const graphs: YagrGraph[] = [
+ {id: 'a', data: [20], dataLabels: {enabled: true, padding: 0}},
+ {id: 'b', data: [10], dataLabels: {enabled: true, padding: 8}},
+ ];
+ const {ctx, u, draw} = createChartMock(graphs);
+ [u.series[1], u.series[2]] = [u.series[2], u.series[1]];
+ u.data[1] = [150];
+ u.data[2] = [100];
+ draw();
+ expect(ctx.fillText.mock.calls).toEqual([
+ ['10', 200, 284],
+ ['20', 200, 200],
+ ]);
+ });
+
+ test('skips hidden series and missing prepared values', () => {
+ const {ctx, u, draw} = createChartMock();
+ u.series[1].show = false;
+ draw();
+ u.series[1].show = true;
+ u.series[1].showInGraph = false;
+ draw();
+ u.series[1].showInGraph = true;
+ u.data[1][0] = null;
+ draw();
+ u.data[1][0] = NaN;
+ draw();
+ expect(ctx.fillText).not.toHaveBeenCalled();
+ });
+
+ test('moves text inside boundaries and skips points outside the viewport', () => {
+ const {ctx, u, chart, draw} = createChartMock();
+ const graph: YagrGraph = {
+ id: 'a',
+ data: [1, 1, 1, 1, 1, 1, 1, 1],
+ dataLabels: {enabled: true},
+ };
+ chart.config.series = shapeYagrConfig({
+ data: {timeline: [], graphs: [graph]},
+ libraryConfig: {},
+ theme: 'light',
+ }).series;
+ u.data[0] = [20, 780, 400, 400, 19, 781, 400, 400];
+ u.data[1] = [200, 200, 20, 500, 200, 200, 19, 501];
+ vi.mocked(u.valToPos).mockImplementation((value) => value);
+ draw();
+ expect(ctx.fillText.mock.calls).toEqual([
+ ['1', 400, 48],
+ ['1', 40, 190],
+ ['1', 760, 190],
+ ['1', 400, 490],
+ ]);
+ });
+
+ test('centers labels wider than the plot', () => {
+ const {ctx, draw} = createChartMock();
+ ctx.measureText.mockReturnValue({
+ width: 800,
+ actualBoundingBoxAscent: 18,
+ actualBoundingBoxDescent: 2,
+ });
+ draw();
+ expect(ctx.fillText).toHaveBeenCalledWith('Plan', 400, 50);
+ });
+
+ test('restores the canvas state if drawing fails', () => {
+ const {ctx, draw} = createChartMock();
+ ctx.fillText.mockImplementation(() => {
+ throw new Error('Drawing failed');
+ });
+ expect(draw).toThrow('Drawing failed');
+ expect(ctx.restore).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/plugins/yagr/__tests__/labels.visual.test.tsx b/src/plugins/yagr/__tests__/labels.visual.test.tsx
new file mode 100644
index 00000000..466a4795
--- /dev/null
+++ b/src/plugins/yagr/__tests__/labels.visual.test.tsx
@@ -0,0 +1,295 @@
+import React from 'react';
+
+import {vi} from 'vitest';
+
+import {render} from '../../../../test-utils/utils.js';
+import {ChartKit} from '../../../components/ChartKit.js';
+import {settings} from '../../../libs/index.js';
+import {YagrPlugin} from '../index.js';
+import type {Yagr, YagrWidgetData} from '../types.js';
+
+const DATA: YagrWidgetData = {
+ data: {
+ timeline: [1, 2, 3],
+ graphs: [
+ {
+ id: 'values',
+ type: 'line',
+ _data: [
+ {value: 10, label: 'Plan'},
+ {value: 20, label: 'Actual'},
+ {value: 30, label: 'Total'},
+ ],
+ dataLabels: {enabled: true},
+ },
+ ],
+ },
+ libraryConfig: {
+ chart: {size: {width: 600, height: 300}},
+ scales: {y: {min: 0, max: 50}},
+ },
+};
+
+const NORMALIZED_LABELS_DATA: YagrWidgetData = {
+ data: {
+ timeline: [1, 2],
+ graphs: [
+ {id: 'a', data: [10, 10], dataLabels: {enabled: true}},
+ {id: 'b', data: [30, 30], dataLabels: {enabled: true}},
+ ],
+ },
+ libraryConfig: {
+ chart: {size: {width: 360, height: 240}},
+ axes: {x: {values: (_u, values) => values.map(String)}},
+ scales: {y: {stacking: true, normalize: true, min: 0, max: 100}},
+ },
+};
+
+const OVERLAPPING_LABELS_DATA: YagrWidgetData = {
+ data: {
+ timeline: [1, 1.8, 2, 2.2, 3],
+ graphs: [
+ {
+ id: 'values',
+ _data: [
+ {value: 25, label: ''},
+ {value: 25, label: 'Point A'},
+ {value: 25, label: 'Point B'},
+ {value: 25, label: 'Point C'},
+ {value: 25, label: ''},
+ ],
+ dataLabels: {enabled: true},
+ },
+ ],
+ },
+ libraryConfig: {
+ chart: {size: {width: 360, height: 240}},
+ axes: {x: {values: (_u, values) => values.map(String)}},
+ scales: {y: {min: 0, max: 50}},
+ },
+};
+
+async function readPng(chart: Yagr) {
+ const image = new Image();
+ image.src = chart.toDataUrl();
+ await image.decode();
+
+ const canvas = document.createElement('canvas');
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Canvas context is unavailable');
+ }
+
+ ctx.drawImage(image, 0, 0);
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
+}
+
+function hasSamePixels(first: ImageData, second: ImageData) {
+ return (
+ first.width === second.width &&
+ first.height === second.height &&
+ first.data.every((value, index) => value === second.data[index])
+ );
+}
+
+describe('Yagr canvas labels integration', () => {
+ beforeEach(() => {
+ settings.set({plugins: [YagrPlugin]});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test('renders normalized line labels at plot boundaries', async () => {
+ let chart: Yagr | undefined;
+ const screen = await render(
+
+ {
+ chart = widget ?? undefined;
+ }}
+ />
+
,
+ {providers: {theme: 'dark'}},
+ );
+ await expect.poll(() => chart?.uplot.data[0]).toEqual(NORMALIZED_LABELS_DATA.data.timeline);
+ await document.fonts.ready;
+ chart?.redraw();
+
+ await expect(screen.getByTestId('label-chart')).toMatchScreenshot();
+ });
+
+ test('hides overlapping point labels by default', async () => {
+ let chart: Yagr | undefined;
+ const screen = await render(
+
+ {
+ chart = widget ?? undefined;
+ }}
+ />
+
,
+ );
+ await expect
+ .poll(() => chart?.uplot.data[0])
+ .toEqual(OVERLAPPING_LABELS_DATA.data.timeline);
+ await document.fonts.ready;
+ chart?.redraw();
+
+ await expect(screen.getByTestId('label-chart')).toMatchScreenshot();
+ });
+
+ test('updates visibility, scale and size through widget props', async () => {
+ const fillText = vi.spyOn(CanvasRenderingContext2D.prototype, 'fillText');
+ const adaptiveData: YagrWidgetData = {
+ ...DATA,
+ libraryConfig: {...DATA.libraryConfig, chart: {size: {adaptive: true}}},
+ };
+ let chart: Yagr | undefined;
+ const renderWidget = (data: YagrWidgetData, width = 600) => (
+
+ {
+ chart = widget ?? undefined;
+ }}
+ />
+
+ );
+ const screen = await render(renderWidget(adaptiveData));
+ await expect.poll(() => chart).toBeDefined();
+ const labels = () =>
+ fillText.mock.calls.filter(([text]) => ['Plan', 'Actual', 'Total'].includes(text));
+
+ const hidden: YagrWidgetData = {
+ ...adaptiveData,
+ data: {
+ ...adaptiveData.data,
+ graphs: adaptiveData.data.graphs.map((graph) => ({...graph, show: false})),
+ },
+ };
+ fillText.mockClear();
+ await screen.rerender(renderWidget(hidden));
+ await expect.poll(() => chart?.uplot.series[1].show).toBe(false);
+ expect(labels()).toEqual([]);
+
+ fillText.mockClear();
+ await screen.rerender(renderWidget(adaptiveData));
+ await expect.poll(() => labels().map(([text]) => text)).toContain('Plan');
+
+ const limitedRange: YagrWidgetData = {
+ ...adaptiveData,
+ libraryConfig: {
+ ...adaptiveData.libraryConfig,
+ scales: {...adaptiveData.libraryConfig.scales, y: {min: 15, max: 25}},
+ },
+ };
+ fillText.mockClear();
+ await screen.rerender(renderWidget(limitedRange));
+ await expect.poll(() => labels().length).toBeGreaterThan(0);
+ expect([...new Set(labels().map(([text]) => text))]).toEqual(['Actual']);
+
+ const previousX = labels()[0][1];
+ fillText.mockClear();
+ await screen.rerender(renderWidget(limitedRange, 400));
+ await expect.poll(() => labels().at(-1)?.[1]).toBeLessThan(previousX);
+ });
+
+ test('exports updated labels and removes them without changing values', async () => {
+ const fillText = vi.spyOn(CanvasRenderingContext2D.prototype, 'fillText');
+ let chart: Yagr | undefined;
+ const screen = await render(
+
+ {
+ chart = widget ?? undefined;
+ }}
+ />
+
,
+ );
+ await expect.poll(() => chart).toBeDefined();
+ if (!chart) {
+ throw new Error('Yagr widget was not loaded');
+ }
+
+ const widget = chart;
+ const readCanvas = () => {
+ const {ctx} = widget.uplot;
+ return ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
+ };
+ const original = await readPng(widget);
+ expect(hasSamePixels(original, readCanvas())).toBe(true);
+
+ const updated: YagrWidgetData = {
+ ...DATA,
+ data: {
+ ...DATA.data,
+ graphs: [
+ {
+ id: 'values',
+ type: 'line',
+ _data: [
+ {value: 15, label: 'Plan'},
+ {value: 25, label: 'Updated'},
+ {value: 35, label: 'Total'},
+ ],
+ dataLabels: {enabled: true},
+ },
+ ],
+ },
+ };
+ const renderWidget = (data: YagrWidgetData) => (
+
+
+
+ );
+
+ fillText.mockClear();
+ await screen.rerender(renderWidget(updated));
+ await expect
+ .poll(() =>
+ fillText.mock.calls.some(
+ ([text], index) =>
+ text === 'Updated' && fillText.mock.contexts[index] === widget.uplot.ctx,
+ ),
+ )
+ .toBe(true);
+ expect(widget.uplot.data[1]).toEqual([15, 25, 35]);
+ await expect
+ .poll(async () => hasSamePixels(await readPng(widget), readCanvas()))
+ .toBe(true);
+
+ const withUpdatedLabels = await readPng(widget);
+ expect(hasSamePixels(original, withUpdatedLabels)).toBe(false);
+
+ const withoutLabels: YagrWidgetData = {
+ ...updated,
+ data: {
+ ...updated.data,
+ graphs: updated.data.graphs.map((graph) => ({
+ ...graph,
+ dataLabels: {enabled: false},
+ })),
+ },
+ };
+ fillText.mockClear();
+ await screen.rerender(renderWidget(withoutLabels));
+ await expect.poll(() => fillText.mock.calls.length).toBeGreaterThan(0);
+ expect(widget.uplot.data[1]).toEqual([15, 25, 35]);
+ expect(fillText.mock.calls.map(([text]) => text)).not.toContain('Updated');
+ await expect
+ .poll(async () => hasSamePixels(await readPng(widget), readCanvas()))
+ .toBe(true);
+ expect(hasSamePixels(withUpdatedLabels, await readPng(widget))).toBe(false);
+ });
+});
diff --git a/src/plugins/yagr/__tests__/utils.test.ts b/src/plugins/yagr/__tests__/utils.test.ts
index 4f92274e..05fbddbd 100644
--- a/src/plugins/yagr/__tests__/utils.test.ts
+++ b/src/plugins/yagr/__tests__/utils.test.ts
@@ -1,7 +1,7 @@
import type {YagrChartOptions} from '@gravity-ui/yagr';
import {getUplotTimezoneAligner, shapeYagrConfig} from '../renderer/utils';
-import type {MinimalValidConfig, YagrWidgetData} from '../types';
+import type {MinimalValidConfig, YagrGraph, YagrWidgetData} from '../types';
const DATA: YagrWidgetData['data'] = {
timeline: [1],
@@ -44,6 +44,118 @@ describe('plugins/yagr/utils', () => {
});
});
+ describe('data labels preparation', () => {
+ const cases: {
+ name: string;
+ graph: YagrGraph;
+ expected: (number | string | null)[];
+ }[] = [
+ {
+ name: 'legacy values',
+ graph: {data: [10, '020', null, 0]},
+ expected: [10, '020', null, 0],
+ },
+ {
+ name: 'labeled points',
+ graph: {
+ _data: [
+ {value: 10, label: 'Plan'},
+ {value: '020'},
+ {value: 15, label: ''},
+ {value: 0, label: null},
+ {value: null, label: 'Missing'},
+ ],
+ },
+ expected: [10, '020', 15, 0, null],
+ },
+ {name: 'empty values', graph: {data: []}, expected: []},
+ {name: 'empty labeled points', graph: {_data: []}, expected: []},
+ {
+ name: 'labeled points override legacy values',
+ graph: {data: [99], _data: [{value: 10}]},
+ expected: [10],
+ },
+ {
+ name: 'empty labeled points fall back to legacy values',
+ graph: {data: [99], _data: []},
+ expected: [99],
+ },
+ {
+ name: 'null legacy values',
+ graph: {data: [null, null]},
+ expected: [null, null],
+ },
+ ];
+
+ test.each(cases)('prepares $name without mutating input', ({graph, expected}) => {
+ const sourceGraph = {...graph, id: 'a', dataLabels: {enabled: true, padding: 0}};
+ const data = {timeline: [1, 2, 3, 4, 5], graphs: [sourceGraph]};
+ const original = structuredClone(data);
+ sourceGraph._data?.forEach(Object.freeze);
+ Object.freeze(sourceGraph._data);
+ Object.freeze(sourceGraph.data);
+ Object.freeze(sourceGraph.dataLabels);
+ Object.freeze(sourceGraph);
+
+ const config = shapeYagrConfig({data, libraryConfig: {}, theme: 'light'});
+
+ expect(config.series[0]).toMatchObject({
+ ...sourceGraph,
+ data: expected,
+ });
+ expect(data).toEqual(original);
+ expect(config.series[0]).not.toBe(sourceGraph);
+ expect(config.series[0].data).not.toBe(sourceGraph.data);
+ });
+
+ test('assigns unique ids without colliding with consumer ids or names', () => {
+ const graphs: YagrGraph[] = [
+ {data: [10]},
+ {id: 'chartkit-series-0', data: [20]},
+ {name: 'Named', _data: [{value: 10, label: 'Plan'}]},
+ {name: 'Named', _data: [{value: 30, label: 'Actual'}]},
+ {name: 'Explicit', data: [40]},
+ {id: 'Explicit', data: [50]},
+ {name: 'chartkit-series-3', data: [60]},
+ ];
+ const originalGraphs = structuredClone(graphs);
+ const config = shapeYagrConfig({
+ data: {timeline: [1], graphs},
+ libraryConfig: {},
+ theme: 'light',
+ });
+
+ expect(new Set(config.series.map((series) => series.id)).size).toBe(graphs.length);
+ expect(config.series[1].id).toBe('chartkit-series-0');
+ expect(config.series[2].id).toBe('Named');
+ expect(config.series[5].id).toBe('Explicit');
+ expect(config.series[6].id).toBe('chartkit-series-3');
+ expect(graphs).toEqual(originalGraphs);
+ });
+
+ test('preserves caller plugins and handlers', () => {
+ const draw = vi.fn();
+ const processed = vi.fn();
+ const plugin = vi.fn(() => ({uplot: {hooks: {}}}));
+ const editUplotOptions = vi.fn((options) => options);
+ const libraryConfig = {
+ plugins: {custom: plugin},
+ hooks: {draw: [draw], processed: [processed]},
+ editUplotOptions,
+ };
+ const config = shapeYagrConfig({data: DATA, libraryConfig, theme: 'light'});
+
+ expect(config.plugins?.custom).toBe(plugin);
+ expect(config.hooks?.draw).toContain(draw);
+ expect(config.hooks?.processed).toContain(processed);
+ expect(libraryConfig.hooks).toEqual({draw: [draw], processed: [processed]});
+
+ const options = {width: 400, height: 300, series: []};
+ expect(config.editUplotOptions?.(options)).toEqual(options);
+ expect(editUplotOptions).toHaveBeenCalledOnce();
+ });
+ });
+
describe('GetUplotTimezoneAligner', () => {
test.each<[YagrChartOptions | undefined, string | undefined, number, number]>([
// UTC
diff --git a/src/plugins/yagr/plugins/YagrDataLabelsPlugin/index.ts b/src/plugins/yagr/plugins/YagrDataLabelsPlugin/index.ts
new file mode 100644
index 00000000..b6f4359a
--- /dev/null
+++ b/src/plugins/yagr/plugins/YagrDataLabelsPlugin/index.ts
@@ -0,0 +1,147 @@
+import type {RawSerieData, YagrPlugin} from '@gravity-ui/yagr';
+
+import type {Yagr, YagrGraph} from '../../types';
+
+type LabeledSeries = RawSerieData & Pick;
+
+type PositionedLabel = {
+ text: string;
+ x: number;
+ y: number;
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+};
+
+function isOverlapping(first: PositionedLabel, second: PositionedLabel) {
+ return (
+ first.left < second.right &&
+ first.right > second.left &&
+ first.top < second.bottom &&
+ first.bottom > second.top
+ );
+}
+
+function drawLabels(yagr: Yagr, u: Yagr['uplot']) {
+ const seriesIndexById = new Map(u.series.map((series, index) => [series.id, index]));
+ const {ctx, bbox} = u;
+ const pixelRatio = ctx.canvas.width / u.width;
+ const style = getComputedStyle(yagr.root);
+ const fontSize = 11 * pixelRatio;
+ const right = bbox.left + bbox.width;
+ const bottom = bbox.top + bbox.height;
+ const placedLabels: PositionedLabel[] = [];
+
+ ctx.save();
+
+ try {
+ ctx.beginPath();
+ ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height);
+ ctx.clip();
+ ctx.font = `bold ${fontSize}px ${style.fontFamily}`;
+ ctx.fillStyle = yagr.utils.colors.parse('var(--g-color-text-secondary)');
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'bottom';
+
+ // Process later input series first so their labels take priority.
+ [...yagr.config.series].reverse().forEach((series: LabeledSeries) => {
+ if (series.id === undefined) {
+ return;
+ }
+
+ const seriesIndex = seriesIndexById.get(series.id);
+ if (!seriesIndex) {
+ return;
+ }
+
+ const uplotSeries = u.series[seriesIndex];
+ if (uplotSeries.show === false || uplotSeries.showInGraph === false) {
+ return;
+ }
+
+ const type =
+ uplotSeries.type ?? series.type ?? yagr.config.chart.series?.type ?? 'line';
+
+ if (type !== 'line' || !series.dataLabels?.enabled) {
+ return;
+ }
+
+ const padding = (series.dataLabels.padding ?? 5) * pixelRatio;
+ const scale = uplotSeries.scale || 'y';
+ const labels: PositionedLabel[] = [];
+
+ series.data.forEach((rawValue, pointIndex) => {
+ const label = series._data?.[pointIndex]?.label ?? String(rawValue);
+ const time = u.data[0][pointIndex];
+ const value = u.data[seriesIndex][pointIndex];
+
+ if (
+ !label ||
+ rawValue === null ||
+ time === undefined ||
+ value === null ||
+ value === undefined ||
+ !Number.isFinite(value)
+ ) {
+ return;
+ }
+
+ const x = u.valToPos(time, 'x', true);
+ const y = u.valToPos(value, scale, true);
+
+ if (
+ !Number.isFinite(x) ||
+ !Number.isFinite(y) ||
+ x < bbox.left ||
+ x > right ||
+ y < bbox.top ||
+ y > bottom
+ ) {
+ return;
+ }
+
+ const metrics = ctx.measureText(label);
+ const halfWidth = Math.min(metrics.width, bbox.width) / 2;
+
+ const labelX = Math.max(bbox.left + halfWidth, Math.min(x, right - halfWidth));
+ const labelY = Math.max(
+ bbox.top + Math.max(0, padding) + metrics.actualBoundingBoxAscent,
+ Math.min(y - padding, bottom - metrics.actualBoundingBoxDescent),
+ );
+
+ labels.push({
+ text: label,
+ x: labelX,
+ y: labelY,
+ left: labelX - metrics.width / 2,
+ right: labelX + metrics.width / 2,
+ top: labelY - metrics.actualBoundingBoxAscent,
+ bottom: labelY + metrics.actualBoundingBoxDescent,
+ });
+ });
+
+ if (!series.dataLabels.allowOverlap) {
+ labels.sort((first, second) => first.top - second.top || first.left - second.left);
+ }
+
+ for (const label of labels) {
+ if (
+ !series.dataLabels.allowOverlap &&
+ placedLabels.some((placed) => isOverlapping(label, placed))
+ ) {
+ continue;
+ }
+
+ ctx.fillText(label.text, label.x, label.y);
+ placedLabels.push(label);
+ }
+ });
+ } finally {
+ ctx.restore();
+ }
+}
+
+export const YagrDataLabelsPlugin: YagrPlugin = (yagr) => ({
+ uplot: {hooks: {draw: [(u) => drawLabels(yagr, u)]}},
+});
diff --git a/src/plugins/yagr/renderer/utils.ts b/src/plugins/yagr/renderer/utils.ts
index 5532d890..f9d22afa 100644
--- a/src/plugins/yagr/renderer/utils.ts
+++ b/src/plugins/yagr/renderer/utils.ts
@@ -3,10 +3,21 @@ import {defaults} from '@gravity-ui/yagr';
import {settings} from '../../../libs';
import {merge} from '../../../utils/merge';
-import type {MinimalValidConfig, Yagr, YagrChartOptions, YagrTheme, YagrWidgetData} from '../types';
+import {YagrDataLabelsPlugin} from '../plugins/YagrDataLabelsPlugin';
+import type {
+ MinimalValidConfig,
+ Yagr,
+ YagrChartOptions,
+ YagrConfig,
+ YagrGraph,
+ YagrTheme,
+ YagrWidgetData,
+} from '../types';
import {getRenderTooltip} from './tooltip';
+const GRAPH_ID_PREFIX = 'chartkit-series';
+
const TOOLTIP_HEADER_CLASS_NAME = '_tooltip-header';
const TOOLTIP_LIST_CLASS_NAME = '_tooltip-list';
@@ -151,12 +162,55 @@ export const getUplotTimezoneAligner =
return new Date(browserDate.valueOf() - uPlotOffset);
};
+function getGraphId(index: number) {
+ return `${GRAPH_ID_PREFIX}-${index}`;
+}
+
+function prepareSeries(graphs: YagrGraph[]) {
+ const knownIds = new Set();
+ const usedIds = new Set();
+
+ for (const graph of graphs) {
+ const id = graph.id || graph.name;
+ if (id) {
+ knownIds.add(id);
+ }
+
+ if (graph.id) {
+ usedIds.add(graph.id);
+ }
+ }
+
+ return graphs.map((graph, index) => {
+ let id = graph.id || graph.name;
+ if (!id || (!graph.id && usedIds.has(id))) {
+ id = getGraphId(index);
+ while (knownIds.has(id)) {
+ id = `_${id}`;
+ }
+ knownIds.add(id);
+ }
+
+ usedIds.add(id);
+
+ return {
+ ...graph,
+ id,
+ data: graph._data?.length
+ ? graph._data.map((point) => point.value)
+ : (graph.data ?? []).slice(),
+ dataLabels: graph.dataLabels && {...graph.dataLabels},
+ };
+ });
+}
+
export const shapeYagrConfig = (args: ShapeYagrConfigArgs): MinimalValidConfig => {
const {data, libraryConfig, theme} = args;
const config: MinimalValidConfig = {
...libraryConfig,
timeline: data.timeline,
- series: data.graphs,
+ series: prepareSeries(data.graphs),
+ plugins: {...libraryConfig.plugins, chartKitDataLabels: YagrDataLabelsPlugin},
};
const {timeZone} = data;
@@ -193,16 +247,23 @@ export const shapeYagrConfig = (args: ShapeYagrConfigArgs): MinimalValidConfig =
config.tooltip.sort = config.tooltip.sort || ((a, b) => b.rowIdx - a.rowIdx);
}
- config.axes = config.axes || {};
+ config.axes = {...config.axes};
const xAxis = config.axes[defaults.DEFAULT_X_SCALE];
- config.editUplotOptions = (opts) => ({
- ...opts,
- tzDate: timeZone ? getUplotTimezoneAligner(config.chart, timeZone) : undefined,
- });
+ config.editUplotOptions = (opts) => {
+ const options = {
+ ...opts,
+ tzDate: timeZone ? getUplotTimezoneAligner(config.chart, timeZone) : opts.tzDate,
+ };
+
+ return libraryConfig.editUplotOptions?.(options) ?? options;
+ };
if (xAxis && !xAxis.values) {
- xAxis.values = getXAxisFormatter(config.chart.timeMultiplier, timeZone);
+ config.axes[defaults.DEFAULT_X_SCALE] = {
+ ...xAxis,
+ values: getXAxisFormatter(config.chart.timeMultiplier, timeZone),
+ };
}
if (!xAxis) {
@@ -211,5 +272,32 @@ export const shapeYagrConfig = (args: ShapeYagrConfigArgs): MinimalValidConfig =
};
}
+ config.hooks = getExportCanvasHooks(config.hooks);
+
return config;
};
+
+// Yagr can retain a detached canvas after updates, so PNG exports need the current canvas.
+// TODO: Remove in the follow-up Yagr upgrade PR.
+// https://github.com/gravity-ui/chartkit/issues/970
+function getExportCanvasHooks(existingHooks: YagrConfig['hooks'] = {}): YagrConfig['hooks'] {
+ let chart: Yagr | undefined;
+
+ return {
+ ...existingHooks,
+ processed: [
+ ...(existingHooks.processed || []),
+ (event) => {
+ chart = event.chart;
+ },
+ ],
+ draw: [
+ ...(existingHooks.draw || []),
+ (u) => {
+ if (chart) {
+ chart.canvas = u.ctx.canvas;
+ }
+ },
+ ],
+ };
+}
diff --git a/src/plugins/yagr/types.ts b/src/plugins/yagr/types.ts
index 9842b39f..47c309b6 100644
--- a/src/plugins/yagr/types.ts
+++ b/src/plugins/yagr/types.ts
@@ -19,9 +19,45 @@ export type YagrWidgetProps = ChartKitProps<'yagr'> & {
id: string;
};
+export interface YagrDataPoint {
+ value: number | string | null;
+ /** Plain text; null or omitted uses the value, an empty string hides the label. */
+ label?: string | null;
+}
+
+export interface YagrDataLabels {
+ /** Show line data labels. Defaults to false. */
+ enabled?: boolean;
+ /**
+ * Distance from the point center to the label's bottom edge in CSS pixels. Defaults to 5.
+ */
+ padding?: number;
+ /**
+ * Draw labels even when they overlap other labels. Defaults to false.
+ */
+ allowOverlap?: boolean;
+}
+
+export type YagrGraph = Omit & {
+ dataLabels?: YagrDataLabels;
+} & (
+ | {
+ data: RawSerieData['data'];
+ _data?: undefined;
+ }
+ | {
+ data?: RawSerieData['data'];
+ /**
+ * @experimental
+ * Raw data with labels
+ */
+ _data: YagrDataPoint[];
+ }
+ );
+
export type YagrWidgetData = {
data: {
- graphs: RawSerieData[];
+ graphs: YagrGraph[];
timeline: number[];
/**
* Allow to setup timezone for X axis and tooltip's header.
diff --git a/vitest.config.ts b/vitest.config.ts
index 28ca981a..530a0bf0 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -17,7 +17,7 @@ export default defineConfig({
browser: {
enabled: true,
headless: true,
- provider: playwright({}),
+ provider: playwright({contextOptions: {locale: 'en-US'}}),
instances: [
{
browser: 'chromium',