@gravity-ui/chartkit 8.12.1 → 8.13.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.
@@ -1,10 +1,10 @@
1
1
  import React from 'react';
2
2
  import type { ChartKitError } from '../../libs';
3
- import type { ChartKitOnError, ChartKitType, ChartKitWidget, RenderError } from '../../types';
3
+ import type { ChartKitOnError, ChartKitProps, ChartKitType, RenderError } from '../../types';
4
4
  type Props = {
5
5
  children: React.ReactNode;
6
6
  onError?: ChartKitOnError;
7
- data: ChartKitWidget[ChartKitType]['data'];
7
+ data: ChartKitProps<ChartKitType>['data'];
8
8
  renderError?: RenderError;
9
9
  };
10
10
  type State = {
@@ -133,4 +133,5 @@ See the `SplitTooltipProps` type for layout control, pane sizing and resizer opt
133
133
 
134
134
  ## Guides
135
135
 
136
+ - [Indicator](./guides/indicator.md) — The indicator displays one or more values with optional titles.
136
137
  - [Testing Guide](./guides/testing.md)
@@ -0,0 +1,187 @@
1
+ # Indicator
2
+
3
+ The indicator displays one or more values with optional titles.
4
+
5
+ Register `IndicatorPlugin` from `@gravity-ui/chartkit/indicator` and pass the
6
+ configuration to `<ChartKit type="indicator" data={data} />`:
7
+
8
+ ```tsx
9
+ import ChartKit, {settings, type ChartKitProps} from '@gravity-ui/chartkit';
10
+ import {IndicatorPlugin} from '@gravity-ui/chartkit/indicator';
11
+
12
+ settings.set({plugins: [IndicatorPlugin]});
13
+
14
+ const data: ChartKitProps<'indicator'>['data'] = {
15
+ data: [
16
+ {
17
+ title: 'Revenue',
18
+ value: {
19
+ value: 1539577,
20
+ numberFormat: {precision: 0, showRankDelimiter: true},
21
+ },
22
+ size: 'm',
23
+ secondaryValue: {
24
+ value: 0.124,
25
+ numberFormat: {
26
+ format: 'percent',
27
+ precision: 1,
28
+ signDisplay: 'exceptZero',
29
+ },
30
+ caption: 'vs the previous month',
31
+ position: 'right',
32
+ color: 'var(--g-color-text-positive)',
33
+ view: 'label',
34
+ arrow: {direction: 'up', ariaLabel: 'Increase'},
35
+ },
36
+ },
37
+ ],
38
+ };
39
+
40
+ <ChartKit type="indicator" data={data} />;
41
+ ```
42
+
43
+ With the English locale, this example displays `1,539,577` as the main value and
44
+ `+12.4%` as the secondary value. Strings render as supplied, including strings that look like numbers.
45
+ The application computes differences, chooses colors and localizes captions.
46
+
47
+ ## Configuration
48
+
49
+ The widget configuration contains a `data` array with one entry per indicator.
50
+ Use `ChartKitProps<'indicator'>['data']` for configurations with `value`
51
+ or a mix of new and legacy items. Use `ChartKitProps<'indicator'>` for the props
52
+ of a wrapper around `<ChartKit type="indicator" />`.
53
+
54
+ `IndicatorWidgetData` and `IndicatorWidgetDataItem` retain the legacy contract
55
+ with required `content.current`, so existing TypeScript wrappers and interfaces
56
+ can keep using them.
57
+
58
+ | Item property | Description | Default |
59
+ | ---------------- | ------------------------------------------------------------------------- | ------------------------------------- |
60
+ | `value` | Main value | Required unless using the legacy form |
61
+ | `secondaryValue` | Additional value | None |
62
+ | `title` | Text displayed above the main value | None |
63
+ | `size` | `s`, `m`, `l`, or `xl`; controls both values | `m` |
64
+ | `nowrap` | Truncate the title to one line and show its full text in a native tooltip | `false` |
65
+
66
+ Both values accept `value`, `formatNumber`, `numberFormat`, and `color`.
67
+
68
+ Set the widget's `defaultColor` to provide a fallback color for primary values.
69
+ `value.color` overrides it. Secondary values have their own `color`.
70
+
71
+ ## Secondary value
72
+
73
+ | Secondary value property | Description | Default |
74
+ | ------------------------ | -------------------------------------------------------------------------------- | ------------------ |
75
+ | `value` | A number or an already formatted string | Required |
76
+ | `formatNumber` | A custom `(value: number) => string` formatter; overrides `numberFormat` | None |
77
+ | `numberFormat` | Formatting options applied to this value | None |
78
+ | `caption` | A caption (`ReactNode`); string captions also have a native tooltip | None |
79
+ | `position` | `bottom` or `right` | `bottom` |
80
+ | `color` | A CSS color for the value and arrow, including theme variables | Primary text color |
81
+ | `view` | `text` or `label`; the label background is a 15% tint of `color` | `text` |
82
+ | `arrow.direction` | `up` or `down`, chosen explicitly by the application | None |
83
+ | `arrow.ariaLabel` | A localized accessible label for the arrow, for example `Increase` or `Decrease` | None |
84
+
85
+ Provide `arrow.ariaLabel` when the arrow conveys information beyond the displayed
86
+ value. The application localizes this label. Without a label, the arrow is
87
+ decorative, so its meaning should be conveyed by the value or caption as well.
88
+
89
+ ## Number formatting
90
+
91
+ Set `value.numberFormat` for the main value and
92
+ `secondaryValue.numberFormat` for the secondary value. The two configurations are
93
+ independent and accept the following options:
94
+
95
+ | Option | Description | Default |
96
+ | ------------------- | ------------------------------------------------------------------------------------------ | -------------------- |
97
+ | `format` | `number` or `percent`; percent multiplies the value by 100 | `number` |
98
+ | `precision` | Fraction digits, or `auto` for adaptive precision | No fixed precision |
99
+ | `showRankDelimiter` | Group thousands | `true` |
100
+ | `unit` | `auto`, `k`, `m`, `b`, `t`, or `null` for no scaling | No scaling |
101
+ | `unitRate` | Scale index: `0` for units, `1` for thousands, through `4` for trillions; overrides `unit` | Determined by `unit` |
102
+ | `multiplier` | Multiply the number before formatting | `1` |
103
+ | `prefix` | Text prepended to the formatted value | Empty string |
104
+ | `postfix` | Text appended to the formatted value | Empty string |
105
+ | `lang` | Locale override | `settings.lang` |
106
+ | `signDisplay` | `auto`, `always`, `never` or `exceptZero` | `auto` |
107
+
108
+ `lang` accepts an `Intl.NumberFormat` locale, including regional tags such as
109
+ `en-US` and `ru-RU`. Unit labels use Russian for `ru` locales and English otherwise.
110
+
111
+ With `format: 'percent'`, the multiplier is always `100`; a supplied `multiplier`
112
+ is ignored.
113
+
114
+ For the numeric main value, formatting priority is:
115
+
116
+ 1. The local `value.formatNumber` callback.
117
+ 2. Explicit `value.numberFormat` options, applied by ChartKit's built-in formatter.
118
+ 3. The widget's `formatNumber` callback. It receives the number and the complete
119
+ `value` object, or the legacy `content.current` object including application metadata.
120
+ 4. Plain text if no callback or options are supplied.
121
+
122
+ For the numeric secondary value, formatting priority is:
123
+
124
+ 1. The local `secondaryValue.formatNumber` callback.
125
+ 2. Explicit `secondaryValue.numberFormat` options.
126
+ 3. Plain text if no callback or options are supplied.
127
+
128
+ Local callbacks receive the number and return its display string, including any
129
+ sign or unit. The widget's callback applies only to main values; it can serve as
130
+ a shared default for multiple indicators. Each value can independently provide
131
+ a local callback or options:
132
+
133
+ ```ts
134
+ const data: ChartKitProps<'indicator'>['data'] = {
135
+ data: [
136
+ {
137
+ value: {value: 1200, formatNumber: (value) => `${value} USD`},
138
+ secondaryValue: {
139
+ value: 0.124,
140
+ numberFormat: {format: 'percent', precision: 1},
141
+ },
142
+ },
143
+ ],
144
+ };
145
+ ```
146
+
147
+ An empty `numberFormat` object `{}` selects the built-in defaults and overrides
148
+ the widget's callback. The built-in formatter uses `settings.lang` unless
149
+ `numberFormat.lang` is specified. Strings bypass all formatters. To display a
150
+ missing value, supply a string such as `value: '—'` and omit `arrow`.
151
+
152
+ `numberFormat.signDisplay` follows `Intl.NumberFormat` semantics: `auto`, `always`,
153
+ `never` or `exceptZero`. For example, `exceptZero` shows a plus sign for positive
154
+ values and omits the sign for values rounded to zero.
155
+
156
+ ## Legacy configuration
157
+
158
+ The legacy form supplies the main value through `content.current.value` and its
159
+ color through the item-level `color` property:
160
+
161
+ ```tsx
162
+ import type {IndicatorWidgetData} from '@gravity-ui/chartkit/indicator';
163
+
164
+ const data: IndicatorWidgetData = {
165
+ data: [
166
+ {
167
+ title: 'Revenue',
168
+ content: {current: {value: 1539577}},
169
+ color: 'var(--g-color-text-positive)',
170
+ },
171
+ ],
172
+ };
173
+
174
+ <ChartKit type="indicator" data={data} formatNumber={(value) => value.toLocaleString('en-US')} />;
175
+ ```
176
+
177
+ The item also accepts `title`, `size`, `nowrap`, and `secondaryValue` as described
178
+ above. The widget's `defaultColor` is used when the item has no color.
179
+
180
+ For a numeric main value, `formatNumber` receives the number and the complete
181
+ `content.current` object, including application metadata. Fields inside
182
+ `content.current` other than `value`, including `color`, `formatNumber`, and `numberFormat`, are
183
+ formatter metadata and do not configure the display. Strings render as supplied.
184
+
185
+ When an item supplies both forms, `value` determines the main value.
186
+ If `value.color` is omitted, the item-level `color` is used. An explicitly
187
+ empty `value.color` uses `defaultColor`.
@@ -1,3 +1,3 @@
1
1
  import { ChartKitPlugin } from '../../types';
2
- export * from './types';
2
+ export type { IndicatorWidgetData, IndicatorWidgetDataItem } from './public-types';
3
3
  export declare const IndicatorPlugin: ChartKitPlugin;
@@ -1,5 +1,4 @@
1
1
  import React from 'react';
2
- export * from './types';
3
2
  export const IndicatorPlugin = {
4
3
  type: 'indicator',
5
4
  renderer: React.lazy(() => import('./renderer/IndicatorWidget')),
@@ -0,0 +1,7 @@
1
+ import type { IndicatorFormatOptions, IndicatorWidgetConfig, IndicatorWidgetConfigItem, NormalizedIndicatorWidgetConfig } from './types';
2
+ /** Return the original formatNumber options, preserving application metadata and object identity. */
3
+ export declare function getValueFormatOptions(item: IndicatorWidgetConfigItem): IndicatorFormatOptions;
4
+ /**
5
+ * Normalize indicator configuration without mutating input, invoking callbacks or logging.
6
+ */
7
+ export declare function normalizeIndicatorData(input: IndicatorWidgetConfig): NormalizedIndicatorWidgetConfig;
@@ -0,0 +1,51 @@
1
+ import { __rest } from "tslib";
2
+ import { CHARTKIT_ERROR_CODE, ChartKitError } from '../../libs';
3
+ /** Return the original formatNumber options, preserving application metadata and object identity. */
4
+ export function getValueFormatOptions(item) {
5
+ if (item.value) {
6
+ return item.value;
7
+ }
8
+ if (item.content) {
9
+ return item.content.current;
10
+ }
11
+ throw new ChartKitError({
12
+ code: CHARTKIT_ERROR_CODE.INVALID_DATA,
13
+ message: 'An indicator item requires value or content.current.',
14
+ });
15
+ }
16
+ function normalizeValue(item) {
17
+ const value = getValueFormatOptions(item);
18
+ if (item.value) {
19
+ if (value.color === undefined && item.color !== undefined) {
20
+ const _a = item.value, { value: rawValue, formatNumber, numberFormat } = _a, rest = __rest(_a, ["value", "formatNumber", "numberFormat"]);
21
+ return Object.assign(Object.assign({}, rest), { value: rawValue, formatNumber, numberFormat, color: item.color });
22
+ }
23
+ return value;
24
+ }
25
+ if (!('color' in value) &&
26
+ !('formatNumber' in value) &&
27
+ !('numberFormat' in value) &&
28
+ item.color === undefined) {
29
+ return value;
30
+ }
31
+ const { value: rawValue, color: _color, formatNumber: _formatNumber, numberFormat: _numberFormat } = value, rest = __rest(value, ["value", "color", "formatNumber", "numberFormat"]);
32
+ return item.color === undefined
33
+ ? Object.assign(Object.assign({}, rest), { value: rawValue }) : Object.assign(Object.assign({}, rest), { value: rawValue, color: item.color });
34
+ }
35
+ /**
36
+ * Normalize indicator configuration without mutating input, invoking callbacks or logging.
37
+ */
38
+ export function normalizeIndicatorData(input) {
39
+ var _a, _b;
40
+ const data = (_a = input.data) === null || _a === void 0 ? void 0 : _a.map((item) => {
41
+ const value = normalizeValue(item);
42
+ if (item.value === value && !('content' in item) && !('color' in item)) {
43
+ return item;
44
+ }
45
+ return Object.assign(Object.assign(Object.assign(Object.assign({ value }, (item.secondaryValue ? { secondaryValue: item.secondaryValue } : {})), (item.title === undefined ? {} : { title: item.title })), (item.size === undefined ? {} : { size: item.size })), (item.nowrap === undefined ? {} : { nowrap: item.nowrap }));
46
+ });
47
+ if ((_b = data === null || data === void 0 ? void 0 : data.every((item, index) => { var _a; return item === ((_a = input.data) === null || _a === void 0 ? void 0 : _a[index]); })) !== null && _b !== void 0 ? _b : true) {
48
+ return input;
49
+ }
50
+ return Object.assign(Object.assign({}, input), { data });
51
+ }
@@ -0,0 +1,50 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { FormatNumberOptions } from '../shared';
3
+ type IndicatorValue = {
4
+ /** Numbers can be formatted; strings are displayed as supplied. */
5
+ value: number | string;
6
+ /** Custom formatter; takes precedence over numberFormat. */
7
+ formatNumber?: (value: number) => string;
8
+ /** Explicit options take precedence over the widget's formatNumber callback. */
9
+ numberFormat?: Omit<FormatNumberOptions, 'labelMode'>;
10
+ /** Any CSS color, including theme variables. */
11
+ color?: string;
12
+ };
13
+ type IndicatorItemOptions = {
14
+ size?: 's' | 'm' | 'l' | 'xl';
15
+ title?: string;
16
+ nowrap?: boolean;
17
+ };
18
+ type IndicatorSecondaryValue = IndicatorValue & {
19
+ caption?: ReactNode;
20
+ /** Defaults to bottom. */
21
+ position?: 'bottom' | 'right';
22
+ /** The label view uses a background derived from color. Defaults to text. */
23
+ view?: 'text' | 'label';
24
+ /** Hidden by default. */
25
+ arrow?: {
26
+ direction: 'up' | 'down';
27
+ /** Localized accessible label, for example "Increase". Omit for a decorative arrow. */
28
+ ariaLabel?: string;
29
+ };
30
+ };
31
+ type LegacyIndicatorContent = {
32
+ /** @deprecated Use value. */
33
+ current: {
34
+ value: string | number;
35
+ } & Record<string, unknown>;
36
+ };
37
+ export type IndicatorWidgetDataItem = IndicatorItemOptions & {
38
+ /** @deprecated Use value in ChartKitProps<'indicator'>['data']. */
39
+ content: LegacyIndicatorContent;
40
+ value?: IndicatorValue;
41
+ /** @deprecated Use value.color. */
42
+ color?: string;
43
+ secondaryValue?: IndicatorSecondaryValue;
44
+ };
45
+ export type IndicatorWidgetData = {
46
+ data?: IndicatorWidgetDataItem[];
47
+ /** Fallback color for primary values only. */
48
+ defaultColor?: string;
49
+ };
50
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,3 @@
1
1
  import React from 'react';
2
- import type { ChartKitProps } from '../../../types';
3
- import type { IndicatorWidgetDataItem } from '../types';
4
- export declare const IndicatorItem: (props: IndicatorWidgetDataItem & {
5
- defaultColor?: string;
6
- formatNumber?: ChartKitProps<"indicator">["formatNumber"];
7
- }) => React.JSX.Element;
2
+ import type { IndicatorItemProps } from '../types';
3
+ export declare const IndicatorItem: (props: IndicatorItemProps) => React.JSX.Element;
@@ -1,15 +1,15 @@
1
1
  import React from 'react';
2
2
  import { block } from '../../../utils/cn';
3
+ import { IndicatorSecondaryValue } from './IndicatorSecondaryValue';
3
4
  const b = block('indicator');
4
5
  export const IndicatorItem = (props) => {
5
- const { formatNumber, content, color, defaultColor, size, title, nowrap } = props;
6
- const mods = { size, nowrap };
7
- const style = { color: color || defaultColor };
8
- let value = content.current.value;
9
- if (formatNumber && typeof value === 'number') {
10
- value = formatNumber(value, content.current);
11
- }
6
+ const { value, size, title, nowrap, secondaryValue } = props;
7
+ const mods = { size, nowrap, right: (secondaryValue === null || secondaryValue === void 0 ? void 0 : secondaryValue.position) === 'right' };
8
+ const style = { color: value.color };
9
+ const valueContent = (React.createElement("div", { className: b('item-value'), style: style }, value.value));
12
10
  return (React.createElement("div", { className: b('item', mods) },
13
11
  title && (React.createElement("div", { className: b('item-title'), title: nowrap ? title : '' }, title)),
14
- React.createElement("div", { className: b('item-value'), style: style }, value)));
12
+ secondaryValue ? (React.createElement("div", { className: b('value-row') },
13
+ valueContent,
14
+ React.createElement(IndicatorSecondaryValue, { secondaryValue: secondaryValue, size: size }))) : (valueContent)));
15
15
  };
@@ -0,0 +1,6 @@
1
+ import React from 'react';
2
+ import type { IndicatorItemProps } from '../types';
3
+ export declare function IndicatorSecondaryValue({ secondaryValue, size, }: {
4
+ secondaryValue: NonNullable<IndicatorItemProps['secondaryValue']>;
5
+ size: IndicatorItemProps['size'];
6
+ }): React.JSX.Element;
@@ -0,0 +1,19 @@
1
+ import React from 'react';
2
+ import { ArrowDown as ArrowDownIcon, ArrowUp as ArrowUpIcon } from '@gravity-ui/icons';
3
+ import { Icon, Label } from '@gravity-ui/uikit';
4
+ import { block } from '../../../utils/cn';
5
+ const b = block('indicator');
6
+ const LABEL_SIZE_BY_INDICATOR_SIZE = { s: 'xs', m: 's', l: 's', xl: 'm' };
7
+ const ICON_SIZE_BY_INDICATOR_SIZE = { s: 12, m: 14, l: 14, xl: 16 };
8
+ export function IndicatorSecondaryValue({ secondaryValue, size, }) {
9
+ const { value, caption, view = 'text', arrow, color } = secondaryValue;
10
+ const labelSize = LABEL_SIZE_BY_INDICATOR_SIZE[size !== null && size !== void 0 ? size : 'm'];
11
+ const arrowIcon = arrow && (React.createElement("span", { className: b('secondary-value-arrow'), role: arrow.ariaLabel ? 'img' : undefined, "aria-label": arrow.ariaLabel },
12
+ React.createElement(Icon, { data: arrow.direction === 'up' ? ArrowUpIcon : ArrowDownIcon, size: ICON_SIZE_BY_INDICATOR_SIZE[size !== null && size !== void 0 ? size : 'm'] })));
13
+ return (React.createElement("div", { className: b('secondary-value', { view }), style: { '--indicator-secondary-value-color': color } },
14
+ React.createElement("div", { className: b('secondary-value-content') },
15
+ view === 'label' ? (React.createElement(Label, { className: b('secondary-value-label'), size: labelSize, icon: arrowIcon }, value)) : (React.createElement("span", { className: b('secondary-value-text'), style: { color } },
16
+ arrowIcon,
17
+ React.createElement("span", null, value))),
18
+ caption !== null && caption !== undefined && caption !== '' && (React.createElement("span", { className: b('secondary-value-caption'), title: typeof caption === 'string' ? caption : undefined }, caption)))));
19
+ }
@@ -59,4 +59,77 @@
59
59
  line-height: 1.2;
60
60
  font-size: 48px;
61
61
  white-space: nowrap;
62
+ }
63
+
64
+ .chartkit-indicator__value-row {
65
+ display: flex;
66
+ flex-direction: column;
67
+ align-items: flex-start;
68
+ gap: var(--g-spacing-2);
69
+ }
70
+
71
+ .chartkit-indicator__item_right .chartkit-indicator__value-row {
72
+ flex-direction: row;
73
+ align-items: baseline;
74
+ gap: var(--g-spacing-3);
75
+ }
76
+
77
+ .chartkit-indicator__item_right .chartkit-indicator__secondary-value_view_label {
78
+ contain: layout;
79
+ }
80
+
81
+ .chartkit-indicator__secondary-value {
82
+ font-size: var(--g-text-body-1-font-size);
83
+ line-height: var(--g-text-body-1-line-height);
84
+ font-weight: var(--g-text-body-font-weight);
85
+ display: block;
86
+ min-width: min-content;
87
+ max-width: 100%;
88
+ }
89
+
90
+ .chartkit-indicator__secondary-value-content {
91
+ display: grid;
92
+ grid-auto-flow: column;
93
+ grid-template-columns: max-content;
94
+ grid-auto-columns: minmax(1em, 1fr);
95
+ align-items: center;
96
+ gap: calc(var(--g-spacing-1) + var(--g-spacing-half));
97
+ min-width: 0;
98
+ }
99
+
100
+ .chartkit-indicator__item_size_l .chartkit-indicator__secondary-value, .chartkit-indicator__item_size_xl .chartkit-indicator__secondary-value {
101
+ font-size: var(--g-text-body-2-font-size);
102
+ line-height: var(--g-text-body-2-line-height);
103
+ }
104
+
105
+ .chartkit-indicator__secondary-value-text {
106
+ display: inline-flex;
107
+ align-items: center;
108
+ gap: var(--g-spacing-half);
109
+ flex-shrink: 0;
110
+ font: inherit;
111
+ white-space: nowrap;
112
+ color: var(--g-color-text-primary);
113
+ }
114
+
115
+ .chartkit-indicator__secondary-value-arrow {
116
+ display: inline-flex;
117
+ flex-shrink: 0;
118
+ }
119
+
120
+ .chartkit-indicator__secondary-value-label {
121
+ color: var(--indicator-secondary-value-color, var(--g-color-text-primary));
122
+ background-color: color-mix(in sRGB, var(--indicator-secondary-value-color, var(--g-color-text-primary)) 15%, transparent);
123
+ }
124
+
125
+ .chartkit-indicator__secondary-value-caption {
126
+ min-width: 0;
127
+ overflow: hidden;
128
+ text-overflow: ellipsis;
129
+ white-space: nowrap;
130
+ color: var(--g-color-text-secondary);
131
+ }
132
+
133
+ .chartkit-indicator__secondary-value-caption:empty {
134
+ display: none;
62
135
  }
@@ -3,7 +3,7 @@ import type { ChartKitWidgetRef } from '../../../types';
3
3
  import './IndicatorWidget.css';
4
4
  declare const IndicatorWidget: React.ForwardRefExoticComponent<{
5
5
  type: "indicator";
6
- data: import("..").IndicatorWidgetData;
6
+ data: import("..").IndicatorWidgetData | import("../types").IndicatorWidgetConfig;
7
7
  id?: string;
8
8
  isMobile?: boolean;
9
9
  onLoad?: ((data?: import("../../..").ChartKitOnLoadData<"indicator"> | undefined) => void) | undefined;
@@ -5,14 +5,15 @@ import { i18n } from '../../../i18n';
5
5
  import { CHARTKIT_ERROR_CODE, ChartKitError } from '../../../libs';
6
6
  import { getChartPerformanceDuration, getRandomCKId, markChartPerformance } from '../../../utils';
7
7
  import { block } from '../../../utils/cn';
8
+ import { getValueFormatOptions, normalizeIndicatorData } from '../normalize';
8
9
  import { IndicatorItem } from './IndicatorItem';
10
+ import { formatValue } from './utils';
9
11
  import './IndicatorWidget.css';
10
12
  const b = block('indicator');
11
- const IndicatorWidget = React.forwardRef(
12
- // _ref needs to avoid this React warning:
13
- // "forwardRef render functions accept exactly two parameters: props and ref"
14
- function IndicatorWidgetInner(props, _ref) {
15
- const { onLoad, formatNumber, data: { data = [], defaultColor }, id, onRender, } = props;
13
+ const IndicatorWidget = React.forwardRef(function IndicatorWidgetInner(props, _ref) {
14
+ const { onLoad, formatNumber, data: config, id, onRender } = props;
15
+ const { data = [], defaultColor } = config;
16
+ const normalizedData = React.useMemo(() => { var _a; return (_a = normalizeIndicatorData(config).data) !== null && _a !== void 0 ? _a : []; }, [config]);
16
17
  const generatedId = React.useMemo(() => `${id}_${getRandomCKId()}`, [data, defaultColor, formatNumber, id]);
17
18
  markChartPerformance(generatedId);
18
19
  React.useLayoutEffect(() => {
@@ -28,7 +29,29 @@ function IndicatorWidgetInner(props, _ref) {
28
29
  message: i18n('error', 'label_no-data'),
29
30
  });
30
31
  }
32
+ const items = normalizedData.map((item, index) => {
33
+ const { value, secondaryValue, title, size, nowrap } = item;
34
+ return {
35
+ title,
36
+ size,
37
+ nowrap,
38
+ value: {
39
+ value: formatValue(value, formatNumber, getValueFormatOptions(data[index])),
40
+ color: value.color || defaultColor,
41
+ },
42
+ secondaryValue: secondaryValue
43
+ ? {
44
+ value: formatValue(secondaryValue),
45
+ color: secondaryValue.color,
46
+ caption: secondaryValue.caption,
47
+ position: secondaryValue.position,
48
+ view: secondaryValue.view,
49
+ arrow: secondaryValue.arrow,
50
+ }
51
+ : undefined,
52
+ };
53
+ });
31
54
  return (React.createElement("div", { className: b() },
32
- React.createElement("div", { className: b('content', CHARTKIT_SCROLLABLE_NODE_CLASSNAME) }, data.map((item, index) => (React.createElement(IndicatorItem, Object.assign({}, item, { key: `${index}-ck-indicator-item`, defaultColor: defaultColor, formatNumber: formatNumber })))))));
55
+ React.createElement("div", { className: b('content', CHARTKIT_SCROLLABLE_NODE_CLASSNAME) }, items.map((item, index) => (React.createElement(IndicatorItem, Object.assign({}, item, { key: `${index}-ck-indicator-item` })))))));
33
56
  });
34
57
  export default IndicatorWidget;
@@ -0,0 +1,4 @@
1
+ import type { IndicatorFormatOptions, NormalizedIndicatorWidgetConfigItem } from '../types';
2
+ export declare function formatValue({ value, formatNumber: localFormatNumber, numberFormat, }: Pick<NormalizedIndicatorWidgetConfigItem['value'], 'value' | 'formatNumber' | 'numberFormat'>, formatNumber?: (value: number, options: {
3
+ value: number | string;
4
+ }) => string, formatOptions?: IndicatorFormatOptions): string;
@@ -0,0 +1,18 @@
1
+ import { settings } from '../../../libs';
2
+ import { formatNumber as defaultFormatNumber } from '../../shared';
3
+ export function formatValue({ value, formatNumber: localFormatNumber, numberFormat, }, formatNumber, formatOptions) {
4
+ var _a;
5
+ if (typeof value === 'string') {
6
+ return value;
7
+ }
8
+ if (localFormatNumber) {
9
+ return localFormatNumber(value);
10
+ }
11
+ if (numberFormat) {
12
+ return defaultFormatNumber(value, Object.assign(Object.assign({}, numberFormat), { lang: (_a = numberFormat.lang) !== null && _a !== void 0 ? _a : settings.get('lang') }));
13
+ }
14
+ if (formatNumber) {
15
+ return formatNumber(value, formatOptions !== null && formatOptions !== void 0 ? formatOptions : { value });
16
+ }
17
+ return String(value);
18
+ }
@@ -1,15 +1,34 @@
1
- export type IndicatorWidgetDataItem = {
2
- content: {
3
- current: {
4
- value: string | number;
5
- } & Record<string, unknown>;
1
+ import type { IndicatorWidgetData, IndicatorWidgetDataItem } from './public-types';
2
+ /**
3
+ * Indicator item before normalization, using either value or legacy content.current.
4
+ * When both are provided, value takes precedence.
5
+ */
6
+ export type IndicatorWidgetConfigItem = IndicatorWidgetDataItem | (Omit<IndicatorWidgetDataItem, 'content' | 'value'> & {
7
+ value: NonNullable<IndicatorWidgetDataItem['value']>;
8
+ content?: IndicatorWidgetDataItem['content'];
9
+ });
10
+ /** Indicator configuration accepted by the widget before normalization. */
11
+ export type IndicatorWidgetConfig = Omit<IndicatorWidgetData, 'data'> & {
12
+ data?: IndicatorWidgetConfigItem[];
13
+ };
14
+ /** Original primary value object passed to the widget's formatNumber callback, including application metadata. */
15
+ export type IndicatorFormatOptions = {
16
+ value: string | number;
17
+ } & Record<string, unknown>;
18
+ /** Indicator item after normalization, with a required value and no legacy content or item-level color. */
19
+ export type NormalizedIndicatorWidgetConfigItem = Omit<IndicatorWidgetConfigItem, 'content' | 'color' | 'value'> & {
20
+ value: NonNullable<IndicatorWidgetDataItem['value']>;
21
+ };
22
+ /** Indicator configuration with normalized items, ready for formatting. */
23
+ export type NormalizedIndicatorWidgetConfig = Omit<IndicatorWidgetConfig, 'data'> & {
24
+ data?: NormalizedIndicatorWidgetConfigItem[];
25
+ };
26
+ /** Rendering props with primary and secondary values formatted as strings. */
27
+ export type IndicatorItemProps = Pick<NormalizedIndicatorWidgetConfigItem, 'title' | 'size' | 'nowrap'> & {
28
+ value: Pick<NormalizedIndicatorWidgetConfigItem['value'], 'color'> & {
29
+ value: string;
30
+ };
31
+ secondaryValue?: Omit<NonNullable<NormalizedIndicatorWidgetConfigItem['secondaryValue']>, 'value' | 'formatNumber' | 'numberFormat'> & {
32
+ value: string;
6
33
  };
7
- color?: string;
8
- size?: 's' | 'm' | 'l' | 'xl';
9
- title?: string;
10
- nowrap?: boolean;
11
- };
12
- export type IndicatorWidgetData = {
13
- data?: IndicatorWidgetDataItem[];
14
- defaultColor?: string;
15
34
  };
@@ -1,5 +1,5 @@
1
1
  import type { FormatNumberOptions, FormatOptions } from './types';
2
- export declare const formatBytes: (value: number, options?: FormatOptions) => string;
3
- export declare const formatDuration: (value: number, options?: FormatOptions) => string;
2
+ export declare const formatBytes: (value: number, options?: FormatOptions, format?: "number" | "percent") => string;
3
+ export declare const formatDuration: (value: number, options?: FormatOptions, format?: "number" | "percent") => string;
4
4
  export declare const getNumberUnitRate: (value: number) => number;
5
5
  export declare const formatNumber: (value: number | string, options?: FormatNumberOptions) => string;
@@ -5,36 +5,52 @@ const i18n = makeInstance('chartkit-units', { ru, en });
5
5
  function getUnitRate(value, exponent, unitsI18nKeys) {
6
6
  let resultUnitRate = 1;
7
7
  while (Math.abs(value / Math.pow(exponent, resultUnitRate)) >= 1 &&
8
- resultUnitRate < 10 &&
9
- i18n(unitsI18nKeys[resultUnitRate])) {
8
+ resultUnitRate < unitsI18nKeys.length) {
10
9
  resultUnitRate++;
11
10
  }
12
11
  return resultUnitRate - 1;
13
12
  }
14
13
  const unitFormatter = ({ exponent, unitsI18nKeys, unitDelimiterI18nKey, }) => {
15
- return function formatUnit(value, options = {}) {
16
- const { precision, unitRate, showRankDelimiter = true, lang } = options;
17
- const i18nLang = i18nInstance.lang;
18
- if (lang) {
19
- i18nInstance.setLang(lang);
20
- }
21
- const resultUnitRate = typeof unitRate === 'number' ? unitRate : getUnitRate(value, exponent, unitsI18nKeys);
22
- let result = value / Math.pow(exponent, resultUnitRate);
14
+ return function formatUnit(value, options = {}, format = 'number') {
15
+ const { precision, unitRate, showRankDelimiter = true, lang, signDisplay } = options;
16
+ const locale = lang !== null && lang !== void 0 ? lang : i18nInstance.lang;
17
+ const isPercent = format === 'percent';
18
+ const resultUnitRate = typeof unitRate === 'number'
19
+ ? unitRate
20
+ : getUnitRate(isPercent ? value * 100 : value, exponent, unitsI18nKeys);
21
+ const scaledValue = value / Math.pow(exponent, resultUnitRate);
22
+ let maximumFractionDigits = 20;
23
23
  if (typeof precision === 'number') {
24
- result = Number(result.toFixed(precision));
24
+ maximumFractionDigits = precision;
25
25
  }
26
- else if (precision === 'auto' && result % 1 !== 0) {
27
- result = Number(result.toFixed(Math.abs(result) > 1 ? 2 : 4));
26
+ else if (precision === 'auto') {
27
+ maximumFractionDigits = Math.abs(scaledValue) > (isPercent ? 0.01 : 1) ? 2 : 4;
28
28
  }
29
- result = new Intl.NumberFormat(lang !== null && lang !== void 0 ? lang : i18nLang, {
29
+ const formatter = new Intl.NumberFormat(locale, {
30
+ style: isPercent ? 'percent' : 'decimal',
30
31
  minimumFractionDigits: typeof precision === 'number' ? precision : 0,
31
- maximumFractionDigits: 20,
32
+ maximumFractionDigits,
32
33
  useGrouping: showRankDelimiter,
33
- }).format(result);
34
- const unit = i18n(unitsI18nKeys[resultUnitRate]);
35
- const delimiter = i18n(unitDelimiterI18nKey);
36
- i18nInstance.setLang(i18nLang);
37
- return `${result}${delimiter}${unit}`;
34
+ signDisplay,
35
+ });
36
+ const result = isPercent
37
+ ? formatter
38
+ .formatToParts(scaledValue)
39
+ .filter(({ type, value: part }) => type !== 'percentSign' && (type !== 'literal' || part.trim() !== ''))
40
+ .map(({ value: part }) => part)
41
+ .join('')
42
+ : formatter.format(scaledValue);
43
+ const unitsLang = new Intl.Locale(locale).language === 'ru' ? 'ru' : 'en';
44
+ const i18nLang = i18nInstance.lang;
45
+ i18nInstance.setLang(unitsLang);
46
+ try {
47
+ const unit = i18n(unitsI18nKeys[resultUnitRate]);
48
+ const delimiter = i18n(unitDelimiterI18nKey);
49
+ return `${result}${delimiter}${unit}`;
50
+ }
51
+ finally {
52
+ i18nInstance.setLang(i18nLang);
53
+ }
38
54
  };
39
55
  };
40
56
  export const formatBytes = unitFormatter({
@@ -76,12 +92,12 @@ export const formatNumber = (value, options = {}) => {
76
92
  let changedMultiplier = multiplier;
77
93
  let prePostfix = '';
78
94
  if (format === 'percent') {
79
- changedMultiplier = 100;
95
+ changedMultiplier = 1;
80
96
  prePostfix = '%';
81
97
  }
82
98
  if (labelMode === 'percent') {
83
99
  prePostfix = '%';
84
100
  }
85
- const formattedValue = baseFormatNumber(Number(value) * changedMultiplier, Object.assign(Object.assign({}, options), { unitRate: unitRate !== null && unitRate !== void 0 ? unitRate : NUMBER_UNIT_RATE_BY_UNIT[unit !== null && unit !== void 0 ? unit : 'default'] }));
101
+ const formattedValue = baseFormatNumber(Number(value) * changedMultiplier, Object.assign(Object.assign({}, options), { unitRate: unitRate !== null && unitRate !== void 0 ? unitRate : NUMBER_UNIT_RATE_BY_UNIT[unit !== null && unit !== void 0 ? unit : 'default'] }), format);
86
102
  return `${prefix}${formattedValue}${prePostfix}${postfix}`;
87
103
  };
@@ -2,6 +2,7 @@ export type FormatOptions = {
2
2
  precision?: number | 'auto';
3
3
  unitRate?: number;
4
4
  showRankDelimiter?: boolean;
5
+ signDisplay?: Intl.NumberFormatOptions['signDisplay'];
5
6
  lang?: string;
6
7
  labelMode?: string;
7
8
  };
@@ -1,5 +1,6 @@
1
1
  import React from 'react';
2
2
  import { ChartKitError } from '../libs';
3
+ import type { IndicatorWidgetConfig } from '../plugins/indicator/types';
3
4
  import type { ChartKitWidget } from './widget';
4
5
  export type { ChartKitHolidays } from './misc';
5
6
  export type ChartKitLang = 'ru' | 'en';
@@ -34,7 +35,7 @@ export type ChartKitOnError = (data: {
34
35
  export type ChartKitRenderPluginLoader = () => React.ReactNode;
35
36
  export type ChartKitProps<T extends ChartKitType> = {
36
37
  type: T;
37
- data: ChartKitWidget[T]['data'];
38
+ data: ChartKitWidget[T]['data'] | (T extends 'indicator' ? IndicatorWidgetConfig : never);
38
39
  id?: string;
39
40
  isMobile?: boolean;
40
41
  onLoad?: (data?: ChartKitOnLoadData<T>) => void;
@@ -1,7 +1,7 @@
1
1
  import type { ChartData } from '@gravity-ui/charts';
2
2
  import type { SplitLayoutType } from '../components/SplitPane/types';
3
3
  import type { Highcharts, HighchartsWidgetData, StringParams } from '../plugins/highcharts/types';
4
- import type { IndicatorWidgetData } from '../plugins/indicator/types';
4
+ import type { IndicatorWidgetData } from '../plugins/indicator/public-types';
5
5
  import type { CustomTooltipProps, Yagr, YagrWidgetData } from '../plugins/yagr/types';
6
6
  export interface ChartKitWidget {
7
7
  yagr: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gravity-ui/chartkit",
3
- "version": "8.12.1",
3
+ "version": "8.13.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",
@@ -64,6 +64,7 @@
64
64
  "@gravity-ui/charts": "^1.73.1",
65
65
  "@gravity-ui/date-utils": "^2.1.0",
66
66
  "@gravity-ui/i18n": "^1.0.0",
67
+ "@gravity-ui/icons": "^2.23.1",
67
68
  "@gravity-ui/yagr": "^5.0.0",
68
69
  "afterframe": "^1.0.2",
69
70
  "lodash": "^4.17.21",
@@ -129,6 +130,7 @@
129
130
  "test:coverage": "vitest run --project unit --coverage",
130
131
  "test:storybook": "vitest run --project storybook",
131
132
  "test:unit": "vitest run --project unit",
133
+ "test:build": "node scripts/check-build.mjs",
132
134
  "test:visual": "vitest run --project visual",
133
135
  "test:docker": "./scripts/playwright-docker.sh npm run test:visual --",
134
136
  "test:docker:update": "./scripts/playwright-docker.sh npm run test:visual -- --update",