@gravity-ui/chartkit 8.13.0 → 8.14.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.
@@ -0,0 +1,2 @@
1
+ import type { YagrPlugin } from '@gravity-ui/yagr';
2
+ export declare const YagrDataLabelsPlugin: YagrPlugin;
@@ -0,0 +1,106 @@
1
+ import { settings } from '../../../../libs';
2
+ import { formatNumber } from '../../../shared';
3
+ function isOverlapping(first, second) {
4
+ return (first.left < second.right &&
5
+ first.right > second.left &&
6
+ first.top < second.bottom &&
7
+ first.bottom > second.top);
8
+ }
9
+ function drawLabels(yagr, u) {
10
+ const seriesIndexById = new Map(u.series.map((series, index) => [series.id, index]));
11
+ const { ctx, bbox } = u;
12
+ const pixelRatio = ctx.canvas.width / u.width;
13
+ const style = getComputedStyle(yagr.root);
14
+ const fontSize = 11 * pixelRatio;
15
+ const right = bbox.left + bbox.width;
16
+ const bottom = bbox.top + bbox.height;
17
+ const placedLabels = [];
18
+ ctx.save();
19
+ try {
20
+ ctx.beginPath();
21
+ ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height);
22
+ ctx.clip();
23
+ ctx.font = `bold ${fontSize}px ${style.fontFamily}`;
24
+ ctx.fillStyle = yagr.utils.colors.parse('var(--g-color-text-secondary)');
25
+ ctx.textAlign = 'center';
26
+ ctx.textBaseline = 'bottom';
27
+ // Process later input series first so their labels take priority.
28
+ [...yagr.config.series].reverse().forEach((series) => {
29
+ var _a, _b, _c, _d;
30
+ if (series.id === undefined) {
31
+ return;
32
+ }
33
+ const seriesIndex = seriesIndexById.get(series.id);
34
+ if (!seriesIndex) {
35
+ return;
36
+ }
37
+ const uplotSeries = u.series[seriesIndex];
38
+ if (uplotSeries.show === false || uplotSeries.showInGraph === false) {
39
+ return;
40
+ }
41
+ if (uplotSeries.type !== 'line' || !((_a = series.dataLabels) === null || _a === void 0 ? void 0 : _a.enabled)) {
42
+ return;
43
+ }
44
+ const padding = ((_b = series.dataLabels.padding) !== null && _b !== void 0 ? _b : 5) * pixelRatio;
45
+ const locale = (_c = yagr.config.chart.appearance) === null || _c === void 0 ? void 0 : _c.locale;
46
+ const format = series.dataLabels.format && Object.assign(Object.assign({}, series.dataLabels.format), { lang: (_d = series.dataLabels.format.lang) !== null && _d !== void 0 ? _d : (typeof locale === 'string' ? locale : settings.get('lang')) });
47
+ const scale = uplotSeries.scale || 'y';
48
+ const labels = [];
49
+ series.data.forEach((rawValue, pointIndex) => {
50
+ var _a, _b;
51
+ const pointLabel = (_b = (_a = series._data) === null || _a === void 0 ? void 0 : _a[pointIndex]) === null || _b === void 0 ? void 0 : _b.label;
52
+ const time = u.data[0][pointIndex];
53
+ const value = u.data[seriesIndex][pointIndex];
54
+ if (pointLabel === '' ||
55
+ rawValue === null ||
56
+ time === undefined ||
57
+ value === null ||
58
+ value === undefined ||
59
+ !Number.isFinite(value)) {
60
+ return;
61
+ }
62
+ const x = u.valToPos(time, 'x', true);
63
+ const y = u.valToPos(value, scale, true);
64
+ if (!Number.isFinite(x) ||
65
+ !Number.isFinite(y) ||
66
+ x < bbox.left ||
67
+ x > right ||
68
+ y < bbox.top ||
69
+ y > bottom) {
70
+ return;
71
+ }
72
+ const label = pointLabel !== null && pointLabel !== void 0 ? pointLabel : (format ? formatNumber(rawValue, format) : String(rawValue));
73
+ const metrics = ctx.measureText(label);
74
+ const halfWidth = Math.min(metrics.width, bbox.width) / 2;
75
+ const labelX = Math.max(bbox.left + halfWidth, Math.min(x, right - halfWidth));
76
+ const labelY = Math.max(bbox.top + Math.max(0, padding) + metrics.actualBoundingBoxAscent, Math.min(y - padding, bottom - metrics.actualBoundingBoxDescent));
77
+ labels.push({
78
+ text: label,
79
+ x: labelX,
80
+ y: labelY,
81
+ left: labelX - metrics.width / 2,
82
+ right: labelX + metrics.width / 2,
83
+ top: labelY - metrics.actualBoundingBoxAscent,
84
+ bottom: labelY + metrics.actualBoundingBoxDescent,
85
+ });
86
+ });
87
+ if (!series.dataLabels.allowOverlap) {
88
+ labels.sort((first, second) => first.top - second.top || first.left - second.left);
89
+ }
90
+ for (const label of labels) {
91
+ if (!series.dataLabels.allowOverlap &&
92
+ placedLabels.some((placed) => isOverlapping(label, placed))) {
93
+ continue;
94
+ }
95
+ ctx.fillText(label.text, label.x, label.y);
96
+ placedLabels.push(label);
97
+ }
98
+ });
99
+ }
100
+ finally {
101
+ ctx.restore();
102
+ }
103
+ }
104
+ export const YagrDataLabelsPlugin = (yagr) => ({
105
+ uplot: { hooks: { draw: [(u) => drawLabels(yagr, u)] } },
106
+ });
@@ -1,15 +1,17 @@
1
1
  import React from 'react';
2
2
  import { useThemeValue } from '@gravity-ui/uikit';
3
- import { shapeYagrConfig } from './utils';
3
+ import { prepareSeries, shapeYagrConfig } from './utils';
4
4
  export const useWidgetData = (props, id) => {
5
5
  const { data, sources, libraryConfig } = props.data;
6
6
  const theme = useThemeValue();
7
+ const series = React.useMemo(() => prepareSeries(data.graphs), [data.graphs]);
7
8
  const config = React.useMemo(() => shapeYagrConfig({
8
9
  data,
10
+ series,
9
11
  libraryConfig,
10
12
  theme,
11
13
  customTooltip: Boolean(props.tooltip),
12
- }), [data, libraryConfig, theme, props.tooltip]);
14
+ }), [data, series, libraryConfig, theme, props.tooltip]);
13
15
  const debug = React.useMemo(() => {
14
16
  const filename = sources
15
17
  ? Object.values(sources)
@@ -1,6 +1,7 @@
1
- import type { MinimalValidConfig, Yagr, YagrChartOptions, YagrTheme, YagrWidgetData } from '../types';
1
+ import type { MinimalValidConfig, Yagr, YagrChartOptions, YagrConfig, YagrGraph, YagrTheme, YagrWidgetData } from '../types';
2
2
  type ShapeYagrConfigArgs = {
3
3
  data: YagrWidgetData['data'];
4
+ series: YagrConfig['series'];
4
5
  libraryConfig: YagrWidgetData['libraryConfig'];
5
6
  theme: YagrTheme;
6
7
  customTooltip?: boolean;
@@ -25,5 +26,34 @@ export declare const detectClickOutside: (args: {
25
26
  * In this function we artificially add shift diff between browser timezone and user timeozne to reset new Date() affects.
26
27
  */
27
28
  export declare const getUplotTimezoneAligner: (chart?: YagrChartOptions, timeZone?: string) => (ts: number) => Date;
29
+ export declare function prepareSeries(graphs: YagrGraph[]): {
30
+ id: string;
31
+ data: (string | number | null)[];
32
+ dataLabels: {
33
+ enabled?: boolean;
34
+ format?: import("../../shared").FormatNumberOptions;
35
+ padding?: number;
36
+ allowOverlap?: boolean;
37
+ } | undefined;
38
+ name?: string;
39
+ scale?: string;
40
+ focus?: boolean;
41
+ precision?: number | undefined;
42
+ title?: string | ((sIdx: number) => string) | undefined;
43
+ color?: string | undefined;
44
+ show?: boolean | undefined;
45
+ cursorOptions?: Pick<import("@gravity-ui/yagr").CursorOptions, "markersSize" | "snapToValues"> | undefined;
46
+ formatter?: ((value: string | number | null, serie: import("uplot").Series) => string) | undefined;
47
+ snapToValues?: (import("@gravity-ui/yagr").SnapToValue | false) | undefined;
48
+ stackGroup?: number | undefined;
49
+ transform?: ((val: number | null | string, series: import("@gravity-ui/yagr").DataSeries[], idx: number) => number | null) | undefined;
50
+ showInTooltip?: boolean | undefined;
51
+ showInLegend?: boolean | undefined;
52
+ showInGraph?: boolean | undefined;
53
+ postProcess?: ((data: (number | null)[], idx: number, y: Yagr) => (number | null)[]) | undefined;
54
+ legendColorKey?: "color" | "lineColor" | undefined;
55
+ type?: import("@gravity-ui/yagr").ChartType;
56
+ _data?: import("..").YagrDataPoint[];
57
+ }[];
28
58
  export declare const shapeYagrConfig: (args: ShapeYagrConfigArgs) => MinimalValidConfig;
29
59
  export {};
@@ -2,7 +2,9 @@ import { dateTime } from '@gravity-ui/date-utils';
2
2
  import { defaults } from '@gravity-ui/yagr';
3
3
  import merge from 'lodash/merge';
4
4
  import { settings } from '../../../libs';
5
+ import { YagrDataLabelsPlugin } from '../plugins/YagrDataLabelsPlugin';
5
6
  import { getRenderTooltip } from './tooltip';
7
+ const GRAPH_ID_PREFIX = 'chartkit-yagr-series';
6
8
  const TOOLTIP_HEADER_CLASS_NAME = '_tooltip-header';
7
9
  const TOOLTIP_LIST_CLASS_NAME = '_tooltip-list';
8
10
  export const synchronizeTooltipTablesCellsWidth = (tooltipContainer) => {
@@ -96,10 +98,41 @@ export const getUplotTimezoneAligner = (chart, timeZone) => (ts) => {
96
98
  const uPlotOffset = (browserTimezone - timestampRealTimezone) * 60 * 1000;
97
99
  return new Date(browserDate.valueOf() - uPlotOffset);
98
100
  };
101
+ function getGraphId(index) {
102
+ return `${GRAPH_ID_PREFIX}-${index}`;
103
+ }
104
+ export function prepareSeries(graphs) {
105
+ const knownIds = new Set();
106
+ const usedIds = new Set();
107
+ for (const graph of graphs) {
108
+ const id = graph.id || graph.name;
109
+ if (id) {
110
+ knownIds.add(id);
111
+ }
112
+ if (graph.id) {
113
+ usedIds.add(graph.id);
114
+ }
115
+ }
116
+ return graphs.map((graph, index) => {
117
+ var _a, _b;
118
+ let id = graph.id || graph.name;
119
+ if (!id || (!graph.id && usedIds.has(id))) {
120
+ id = getGraphId(index);
121
+ while (knownIds.has(id)) {
122
+ id = `_${id}`;
123
+ }
124
+ knownIds.add(id);
125
+ }
126
+ usedIds.add(id);
127
+ return Object.assign(Object.assign({}, graph), { id, data: ((_a = graph._data) === null || _a === void 0 ? void 0 : _a.length)
128
+ ? graph._data.map((point) => point.value)
129
+ : ((_b = graph.data) !== null && _b !== void 0 ? _b : []).slice(), dataLabels: graph.dataLabels && Object.assign({}, graph.dataLabels) });
130
+ });
131
+ }
99
132
  export const shapeYagrConfig = (args) => {
100
133
  var _a, _b;
101
- const { data, libraryConfig, theme } = args;
102
- const config = Object.assign(Object.assign({}, libraryConfig), { timeline: data.timeline, series: data.graphs });
134
+ const { data, series, libraryConfig, theme } = args;
135
+ const config = Object.assign(Object.assign({}, libraryConfig), { timeline: data.timeline, series, plugins: Object.assign(Object.assign({}, libraryConfig.plugins), { chartKitDataLabels: YagrDataLabelsPlugin }) });
103
136
  const { timeZone } = data;
104
137
  const chart = {
105
138
  appearance: {
@@ -126,16 +159,40 @@ export const shapeYagrConfig = (args) => {
126
159
  */
127
160
  config.tooltip.sort = config.tooltip.sort || ((a, b) => b.rowIdx - a.rowIdx);
128
161
  }
129
- config.axes = config.axes || {};
162
+ config.axes = Object.assign({}, config.axes);
130
163
  const xAxis = config.axes[defaults.DEFAULT_X_SCALE];
131
- config.editUplotOptions = (opts) => (Object.assign(Object.assign({}, opts), { tzDate: timeZone ? getUplotTimezoneAligner(config.chart, timeZone) : undefined }));
164
+ config.editUplotOptions = (opts) => {
165
+ var _a, _b;
166
+ const options = Object.assign(Object.assign({}, opts), { tzDate: timeZone ? getUplotTimezoneAligner(config.chart, timeZone) : opts.tzDate });
167
+ return (_b = (_a = libraryConfig.editUplotOptions) === null || _a === void 0 ? void 0 : _a.call(libraryConfig, options)) !== null && _b !== void 0 ? _b : options;
168
+ };
132
169
  if (xAxis && !xAxis.values) {
133
- xAxis.values = getXAxisFormatter(config.chart.timeMultiplier, timeZone);
170
+ config.axes[defaults.DEFAULT_X_SCALE] = Object.assign(Object.assign({}, xAxis), { values: getXAxisFormatter(config.chart.timeMultiplier, timeZone) });
134
171
  }
135
172
  if (!xAxis) {
136
173
  config.axes[defaults.DEFAULT_X_SCALE] = {
137
174
  values: getXAxisFormatter(config.chart.timeMultiplier, timeZone),
138
175
  };
139
176
  }
177
+ config.hooks = getExportCanvasHooks(config.hooks);
140
178
  return config;
141
179
  };
180
+ // Yagr can retain a detached canvas after updates, so PNG exports need the current canvas.
181
+ // TODO: Remove in the follow-up Yagr upgrade PR.
182
+ // https://github.com/gravity-ui/chartkit/issues/970
183
+ function getExportCanvasHooks(existingHooks = {}) {
184
+ let chart;
185
+ return Object.assign(Object.assign({}, existingHooks), { processed: [
186
+ ...(existingHooks.processed || []),
187
+ (event) => {
188
+ chart = event.chart;
189
+ },
190
+ ], draw: [
191
+ ...(existingHooks.draw || []),
192
+ (u) => {
193
+ if (chart) {
194
+ chart.canvas = u.ctx.canvas;
195
+ }
196
+ },
197
+ ] });
198
+ }
@@ -1,6 +1,7 @@
1
1
  import type { MinimalValidConfig, RawSerieData, YagrConfig } from '@gravity-ui/yagr';
2
2
  import type Yagr from '@gravity-ui/yagr';
3
3
  import type { ChartKitProps } from '../../types';
4
+ import type { FormatNumberOptions } from '../shared';
4
5
  export type { default as Yagr } from '@gravity-ui/yagr';
5
6
  export type * from '@gravity-ui/yagr';
6
7
  export type { YagrReactRef } from '@gravity-ui/yagr/react';
@@ -10,9 +11,38 @@ export interface CustomTooltipProps {
10
11
  export type YagrWidgetProps = ChartKitProps<'yagr'> & {
11
12
  id: string;
12
13
  };
14
+ export interface YagrDataPoint {
15
+ value: number | string | null;
16
+ /**
17
+ * Plain text; null or omitted formats the value, an empty string hides the label.
18
+ */
19
+ label?: string | null;
20
+ }
21
+ export interface YagrDataLabels {
22
+ /** Show line data labels. Defaults to false. */
23
+ enabled?: boolean;
24
+ /**
25
+ * Number formatting for values without an explicit label.
26
+ * `lang` defaults to the chart locale.
27
+ */
28
+ format?: FormatNumberOptions;
29
+ /**
30
+ * Distance from the point center to the label's bottom edge in CSS pixels. Defaults to 5.
31
+ */
32
+ padding?: number;
33
+ /**
34
+ * Draw labels even when they overlap other labels. Defaults to false.
35
+ */
36
+ allowOverlap?: boolean;
37
+ }
38
+ export type YagrGraph = RawSerieData & {
39
+ dataLabels?: YagrDataLabels;
40
+ /** Experimental raw data with labels. */
41
+ _data?: YagrDataPoint[];
42
+ };
13
43
  export type YagrWidgetData = {
14
44
  data: {
15
- graphs: RawSerieData[];
45
+ graphs: YagrGraph[];
16
46
  timeline: number[];
17
47
  /**
18
48
  * Allow to setup timezone for X axis and tooltip's header.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gravity-ui/chartkit",
3
- "version": "8.13.0",
3
+ "version": "8.14.0",
4
4
  "description": "Plugin-based React component that renders charts from multiple charting libraries, such as Gravity Charts and Yagr, through a single ChartKit API, with mobile-friendly tooltips and custom plugin support",
5
5
  "keywords": [
6
6
  "charts",