= {
+ render: ({color, size, title, nowrap, secondaryValuePosition, secondaryValue}) => {
+ settings.set({plugins: [IndicatorPlugin]});
+
+ return (
+
+
+
+ );
+ },
+ args: {
+ ...Showcase.args,
+ secondaryValuePosition: 'bottom',
+ secondaryValue: {
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1, signDisplay: 'exceptZero'},
+ caption: 'vs the previous month',
+ arrow: {direction: 'up', ariaLabel: 'Increase'},
+ color: 'var(--g-color-text-positive)',
+ view: 'label',
+ },
+ },
+ argTypes: {
+ ...Showcase.argTypes,
+ secondaryValuePosition: {
+ control: 'radio',
+ options: ['bottom', 'right'],
+ },
+ secondaryValue: {
+ control: 'object',
+ },
+ },
+};
diff --git a/src/plugins/indicator/__tests__/Indicator.visual.test.tsx b/src/plugins/indicator/__tests__/Indicator.visual.test.tsx
index 8e16c2c1..8bf2b1af 100644
--- a/src/plugins/indicator/__tests__/Indicator.visual.test.tsx
+++ b/src/plugins/indicator/__tests__/Indicator.visual.test.tsx
@@ -1,10 +1,13 @@
import React from 'react';
-import {render} from '../../../../test-utils/utils.js';
-import {ChartKit} from '../../../components/ChartKit.js';
-import {settings} from '../../../libs/index.js';
-import {IndicatorPlugin} from '../index.js';
-import type {IndicatorWidgetData} from '../types.js';
+import {page} from 'vitest/browser';
+
+import {IndicatorPlugin} from '../';
+import {render} from '../../../../test-utils/utils';
+import {ChartKit} from '../../../components/ChartKit';
+import {settings} from '../../../libs';
+import type {IndicatorWidgetData, IndicatorWidgetDataItem} from '../public-types';
+import type {IndicatorWidgetConfigItem} from '../types';
const indicatorData: IndicatorWidgetData = {
data: [
@@ -36,6 +39,27 @@ describe('Indicator visual tests', () => {
await expect.element(screen.getByText('1539577973')).toBeVisible();
await expect(screen.getByTestId('indicator-wrapper')).toMatchScreenshot();
+
+ const legacyMarkup = screen.container.querySelector('.chartkit-indicator')?.innerHTML;
+ await screen.rerender(
+
+
+
,
+ );
+ await expect.element(screen.getByText('1539577973')).toBeVisible();
+ expect(screen.container.querySelector('.chartkit-indicator')?.innerHTML).toBe(legacyMarkup);
});
test('no data state', async () => {
@@ -54,4 +78,410 @@ describe('Indicator visual tests', () => {
await expect.element(screen.getByText('No data')).toBeVisible();
});
+
+ test('secondary value formatting and overflow', async () => {
+ settings.set({plugins: [IndicatorPlugin]});
+ const item = {
+ title: 'Revenue',
+ content: {current: {value: 1200}},
+ secondaryValue: {
+ value: 0.124,
+ numberFormat: {
+ format: 'percent',
+ precision: 1,
+ signDisplay: 'exceptZero',
+ },
+ position: 'right',
+ caption: 'vs the previous month',
+ color: 'var(--g-color-text-positive)',
+ view: 'label',
+ arrow: {direction: 'up', ariaLabel: 'Increase'},
+ },
+ } satisfies IndicatorWidgetDataItem;
+ const renderIndicator = (
+ dataItem: IndicatorWidgetConfigItem,
+ width: number | string = '100%',
+ ) => (
+
+
+
+ );
+ const screen = await render(renderIndicator(item), options);
+
+ await expect.element(screen.getByText('+12.4%', {exact: true})).toBeVisible();
+ await expect.element(screen.getByRole('img', {name: 'Increase'})).toBeVisible();
+
+ const legacyMarkup = screen.container.querySelector('.chartkit-indicator')?.innerHTML;
+ await screen.rerender(
+ renderIndicator({
+ title: 'Revenue',
+ value: {value: 1200},
+ secondaryValue: {
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1, signDisplay: 'exceptZero'},
+ position: 'right',
+ caption: 'vs the previous month',
+ color: 'var(--g-color-text-positive)',
+ view: 'label',
+ arrow: {direction: 'up', ariaLabel: 'Increase'},
+ },
+ }),
+ );
+ await expect.element(screen.getByRole('img', {name: 'Increase'})).toBeVisible();
+ expect(screen.container.querySelector('.chartkit-indicator')?.innerHTML).toBe(legacyMarkup);
+
+ for (const {width, size} of [
+ {width: 300, size: 'm'},
+ {width: 400, size: 'xl'},
+ {width: 100, size: 'm'},
+ ] as const) {
+ await screen.rerender(
+ renderIndicator(
+ {
+ ...item,
+ size,
+ content: {current: {value: 1539577973}},
+ },
+ width,
+ ),
+ );
+
+ const text = screen.getByText('+12.4%', {exact: true}).element();
+ const secondary = screen.container.querySelector(
+ '.chartkit-indicator__secondary-value',
+ );
+ const caption = screen.getByText('vs the previous month', {exact: true}).element();
+ const scrollable = screen.container.querySelector('.chartkit-indicator__content');
+ if (!secondary || !scrollable) {
+ throw new Error('Indicator content is missing');
+ }
+
+ const secondaryRect = secondary.getBoundingClientRect();
+ const textRect = text.getBoundingClientRect();
+ expect(textRect.left).toBeGreaterThanOrEqual(secondaryRect.left);
+ expect(textRect.right).toBeLessThanOrEqual(secondaryRect.right);
+ expect(caption.getBoundingClientRect().width).toBeGreaterThan(0);
+ expect(caption.getAttribute('title')).toBe('vs the previous month');
+ expect(scrollable.scrollWidth).toBeGreaterThan(scrollable.clientWidth);
+
+ scrollable.scrollLeft = scrollable.scrollWidth;
+ await expect
+ .poll(() => {
+ const viewport = scrollable.getBoundingClientRect();
+ const value = text.getBoundingClientRect();
+ const captionRect = caption.getBoundingClientRect();
+ return (
+ value.left >= viewport.left &&
+ value.right <= viewport.right &&
+ captionRect.left >= viewport.left &&
+ captionRect.right <= viewport.right
+ );
+ })
+ .toBe(true);
+ }
+ });
+
+ test('secondary value below: text with a downward arrow', async () => {
+ settings.set({plugins: [IndicatorPlugin], lang: 'en'});
+
+ const screen = await render(
+
+
+
,
+ options,
+ );
+
+ await expect.element(screen.getByText('-12.4%', {exact: true})).toBeVisible();
+ await expect.element(screen.getByRole('img', {name: 'Decrease'})).toBeVisible();
+
+ const mainRect = screen.getByText('1200', {exact: true}).element().getBoundingClientRect();
+ const secondaryRect = screen
+ .getByText('-12.4%', {exact: true})
+ .element()
+ .getBoundingClientRect();
+ expect(secondaryRect.top).toBeGreaterThanOrEqual(mainRect.bottom);
+
+ await expect(screen.getByTestId('indicator-secondary-wrapper')).toMatchScreenshot();
+ });
+
+ test('secondary value', async () => {
+ await page.viewport(1000, 600);
+ settings.set({plugins: [IndicatorPlugin]});
+ const sizes = [
+ {size: 's', labelHeight: 20, iconSize: 12, captionSize: 13},
+ {size: 'm', labelHeight: 24, iconSize: 14, captionSize: 13},
+ {size: 'l', labelHeight: 24, iconSize: 14, captionSize: 15},
+ {size: 'xl', labelHeight: 28, iconSize: 16, captionSize: 15},
+ ] as const;
+ const screen = await render(
+
+ ({
+ size,
+ title: `Revenue (${size})`,
+ value: {value: '$112.4M'},
+ secondaryValue: {
+ value: '+13.4%',
+ position: 'right',
+ caption: 'vs the previous month',
+ color: 'var(--g-color-text-positive)',
+ view: 'label',
+ arrow: {direction: 'up', ariaLabel: 'Increase'},
+ },
+ })),
+ }}
+ />
+
,
+ options,
+ );
+
+ function getBaseline(element: Element) {
+ const marker = document.createElement('span');
+ marker.style.cssText =
+ 'display: inline-block; width: 0; height: 0; vertical-align: baseline';
+ element.append(marker);
+ const baseline = marker.getBoundingClientRect().top;
+ marker.remove();
+ return baseline;
+ }
+
+ for (const [index, item] of screen.container
+ .querySelectorAll('.chartkit-indicator__item')
+ .entries()) {
+ const expected = sizes[index];
+ const main = item.querySelector('.chartkit-indicator__item-value');
+ const label = item.querySelector('.g-label');
+ const labelText = item.querySelector('.g-label__content');
+ const icon = item.querySelector('.chartkit-indicator__secondary-value-arrow svg');
+ const caption = item.querySelector('.chartkit-indicator__secondary-value-caption');
+ if (!main || !label || !labelText || !icon || !caption) {
+ throw new Error('Indicator content is missing');
+ }
+ expect(getComputedStyle(labelText).fontSize).toBe('13px');
+ expect(getComputedStyle(labelText).lineHeight).toBe(`${expected.labelHeight}px`);
+ expect(getComputedStyle(caption).fontSize).toBe(`${expected.captionSize}px`);
+ expect(icon.getAttribute('width')).toBe(String(expected.iconSize));
+ expect(icon.getAttribute('height')).toBe(String(expected.iconSize));
+ const baseline = getBaseline(main);
+ const labelRect = label.getBoundingClientRect();
+ const captionRect = caption.getBoundingClientRect();
+ expect(labelRect.height).toBe(expected.labelHeight);
+ expect(Math.abs(labelRect.bottom - baseline)).toBeLessThan(1);
+ expect(
+ Math.abs(
+ captionRect.top +
+ captionRect.height / 2 -
+ (labelRect.top + labelRect.height / 2),
+ ),
+ ).toBeLessThan(1);
+ }
+
+ await expect(screen.getByTestId('indicator-alignment-wrapper')).toMatchScreenshot();
+ await page.viewport(400, 280);
+ });
+
+ test('secondary value below: label without color or caption', async () => {
+ settings.set({plugins: [IndicatorPlugin], lang: 'en'});
+
+ const screen = await render(
+
+
+
,
+ options,
+ );
+
+ await expect.element(screen.getByText('12.4%', {exact: true})).toBeVisible();
+
+ const mainRect = screen.getByText('1200', {exact: true}).element().getBoundingClientRect();
+ const secondaryRect = screen
+ .getByText('12.4%', {exact: true})
+ .element()
+ .getBoundingClientRect();
+ expect(secondaryRect.top).toBeGreaterThanOrEqual(mainRect.bottom);
+
+ await expect(screen.getByTestId('indicator-secondary-wrapper')).toMatchScreenshot();
+ });
+
+ test('independent number formats', async () => {
+ settings.set({plugins: [IndicatorPlugin], lang: 'en'});
+ const formatNumber = vi.fn((_value: number, _options?: unknown) => 'custom result');
+ const current = {
+ value: 1234.56,
+ precision: 2,
+ customMetadata: 'main value',
+ };
+ const mainNumberFormat = {precision: 0, showRankDelimiter: true, postfix: ' USD'};
+ const secondaryValue: NonNullable = {
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1, signDisplay: 'exceptZero'},
+ };
+ const renderIndicator = (item: IndicatorWidgetConfigItem) => (
+
+
+
+ );
+ const screen = await render(
+ renderIndicator({
+ value: {value: current.value, numberFormat: mainNumberFormat},
+ secondaryValue,
+ }),
+ options,
+ );
+
+ await expect.element(screen.getByText('1,235 USD', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('+12.4%', {exact: true})).toBeVisible();
+ expect(formatNumber).not.toHaveBeenCalled();
+ await expect(screen.getByTestId('indicator-formats-wrapper')).toMatchScreenshot();
+
+ await screen.rerender(renderIndicator({content: {current}, secondaryValue}));
+
+ await expect.element(screen.getByText('custom result', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('+12.4%', {exact: true})).toBeVisible();
+ expect(formatNumber).toHaveBeenCalledExactlyOnceWith(current.value, current);
+ expect(formatNumber.mock.calls[0][1]).toBe(current);
+
+ formatNumber.mockClear();
+ await screen.rerender(
+ renderIndicator({
+ value: {value: current.value, numberFormat: mainNumberFormat},
+ secondaryValue: {value: secondaryValue.value},
+ }),
+ );
+
+ await expect.element(screen.getByText('1,235 USD', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('0.124', {exact: true})).toBeVisible();
+ expect(formatNumber).not.toHaveBeenCalled();
+
+ formatNumber.mockClear();
+ const value = {value: 0, color: 'green'};
+ await screen.rerender(renderIndicator({value, secondaryValue}));
+ await expect.element(screen.getByText('custom result', {exact: true})).toBeVisible();
+ expect(formatNumber).toHaveBeenCalledExactlyOnceWith(0, value);
+ expect(formatNumber.mock.calls[0][1]).toBe(value);
+
+ formatNumber.mockClear();
+ const localMainFormatter = vi.fn(() => 'main callback');
+ const localSecondaryFormatter = vi.fn(() => 'secondary callback');
+ await screen.rerender(
+ renderIndicator({
+ value: {
+ value: current.value,
+ formatNumber: localMainFormatter,
+ numberFormat: mainNumberFormat,
+ },
+ secondaryValue: {...secondaryValue, formatNumber: localSecondaryFormatter},
+ }),
+ );
+ await expect.element(screen.getByText('main callback', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('secondary callback', {exact: true})).toBeVisible();
+ expect(localMainFormatter).toHaveBeenCalledExactlyOnceWith(current.value);
+ expect(localSecondaryFormatter).toHaveBeenCalledExactlyOnceWith(secondaryValue.value);
+ expect(formatNumber).not.toHaveBeenCalled();
+ });
+
+ test('legacy formatter metadata does not override the default color', async () => {
+ settings.set({plugins: [IndicatorPlugin]});
+ const current = {
+ value: 42,
+ color: 'red',
+ numberFormat: 'formatter metadata',
+ formatNumber: vi.fn(() => 'formatter metadata'),
+ customMetadata: 'legacy',
+ };
+ const formatNumber = vi.fn((value: number, _options?: unknown) => String(value));
+ const screen = await render(
+ ,
+ options,
+ );
+ await expect.element(screen.getByText('42', {exact: true})).toBeVisible();
+ expect(screen.getByText('42', {exact: true}).element().getAttribute('style')).toBe(
+ 'color: blue;',
+ );
+ expect(formatNumber.mock.calls[0][1]).toBe(current);
+ expect(current.formatNumber).not.toHaveBeenCalled();
+ });
+
+ test('updates when a new configuration reuses the data array', async () => {
+ settings.set({plugins: [IndicatorPlugin]});
+ const items: IndicatorWidgetDataItem[] = [
+ {
+ content: {current: {value: 42}},
+ color: 'red',
+ title: 'Before',
+ },
+ ];
+ const screen = await render(, options);
+ await expect.element(screen.getByText('42', {exact: true})).toBeVisible();
+
+ items[0] = {content: {current: {value: 43}}, color: 'blue', title: 'After'};
+ await screen.rerender();
+
+ await expect.element(screen.getByText('43', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('After', {exact: true})).toBeVisible();
+ expect(screen.getByText('43', {exact: true}).element().getAttribute('style')).toBe(
+ 'color: blue;',
+ );
+ });
+
+ test('updates formatted values when only the formatter changes', async () => {
+ settings.set({plugins: [IndicatorPlugin]});
+ const current = {value: 42, numberFormat: {precision: 2}, customMetadata: 'source'};
+ const config = {data: [{content: {current}, secondaryValue: {value: 7}}]};
+ const firstFormatter = vi.fn((value: number, _options?: unknown) => `first:${value}`);
+ const screen = await render(
+ ,
+ options,
+ );
+ await expect.element(screen.getByText('first:42', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('7', {exact: true})).toBeVisible();
+ expect(firstFormatter.mock.calls[0][1]).toBe(current);
+ firstFormatter.mockClear();
+
+ const nextFormatter = vi.fn((value: number, _options?: unknown) => `next:${value}`);
+ await screen.rerender(
+ ,
+ );
+ await expect.element(screen.getByText('next:42', {exact: true})).toBeVisible();
+ await expect.element(screen.getByText('7', {exact: true})).toBeVisible();
+ expect(firstFormatter).not.toHaveBeenCalled();
+ expect(nextFormatter).toHaveBeenCalledExactlyOnceWith(42, current);
+ expect(nextFormatter.mock.calls[0][1]).toBe(current);
+ });
});
diff --git a/src/plugins/indicator/__tests__/normalize.test.ts b/src/plugins/indicator/__tests__/normalize.test.ts
new file mode 100644
index 00000000..e4896403
--- /dev/null
+++ b/src/plugins/indicator/__tests__/normalize.test.ts
@@ -0,0 +1,100 @@
+import {getValueFormatOptions, normalizeIndicatorData} from '../normalize';
+import type {IndicatorWidgetConfig} from '../types';
+
+describe('normalizeIndicatorData', () => {
+ test('converts aliases, preserves metadata and references, and is idempotent', () => {
+ const modern = Object.freeze({value: Object.freeze({value: 0})});
+ const custom = {callback: vi.fn()};
+ const current = Object.freeze({
+ value: 1200,
+ color: 'metadata',
+ numberFormat: {precision: 2},
+ custom,
+ });
+ const secondaryValue = Object.freeze({value: '—', caption: 'Comparison'});
+ const legacy = Object.freeze({
+ content: Object.freeze({current}),
+ color: 'blue',
+ title: 'Revenue',
+ size: 'xl' as const,
+ nowrap: true,
+ secondaryValue,
+ });
+ const input = Object.freeze({
+ data: [modern, legacy],
+ defaultColor: 'black',
+ }) satisfies IndicatorWidgetConfig;
+ Object.freeze(input.data);
+
+ const data = normalizeIndicatorData(input);
+ const converted = data.data?.[1];
+ expect(converted).toEqual({
+ value: {value: 1200, color: 'blue', custom},
+ title: 'Revenue',
+ size: 'xl',
+ nowrap: true,
+ secondaryValue,
+ });
+ expect(data.defaultColor).toBe('black');
+ expect(data.data?.[0]).toBe(modern);
+ expect(converted?.value).toHaveProperty('custom', custom);
+ expect(converted?.secondaryValue).toBe(secondaryValue);
+ expect(getValueFormatOptions(legacy)).toBe(current);
+ expect(custom.callback).not.toHaveBeenCalled();
+ expect(normalizeIndicatorData(data)).toBe(data);
+ });
+
+ test.each([
+ {color: undefined, expected: 'red'},
+ {color: '', expected: ''},
+ ])('prefers primary value fields with color $color', ({color, expected}) => {
+ const value = {value: 0, color};
+ const item = {value, content: {current: {value: 500}}, color: 'red'};
+ const data = normalizeIndicatorData({data: [item]});
+ expect(data.data?.[0]).toEqual({value: {value: 0, color: expected}});
+ expect(getValueFormatOptions(item)).toBe(value);
+ });
+
+ test('handles missing data', () => {
+ const input = {};
+ expect(normalizeIndicatorData(input)).toBe(input);
+ });
+
+ test('keeps legacy formatNumber fields as formatter metadata', () => {
+ const formatNumber = vi.fn();
+ const current = {value: 42, formatNumber};
+ const item = {content: {current}};
+ const data = normalizeIndicatorData({data: [item]});
+ expect(data.data?.[0]?.value).toEqual({value: 42});
+ expect(getValueFormatOptions(item)).toBe(current);
+ expect(formatNumber).not.toHaveBeenCalled();
+ });
+
+ test('preserves prototype getters when applying an item color', () => {
+ const formatNumber = vi.fn(() => 'custom');
+ const numberFormat = {precision: 2};
+ class Value {
+ get value() {
+ return 42;
+ }
+ get formatNumber() {
+ return formatNumber;
+ }
+ get numberFormat() {
+ return numberFormat;
+ }
+ }
+ const item = {value: new Value(), color: 'green'};
+ const data = normalizeIndicatorData({data: [item]});
+ expect(data.data?.[0]?.value).toEqual({
+ value: 42,
+ formatNumber,
+ numberFormat,
+ color: 'green',
+ });
+ expect(data.data?.[0]?.value.formatNumber).toBe(formatNumber);
+ expect(data.data?.[0]?.value.numberFormat).toBe(numberFormat);
+ expect(getValueFormatOptions(item)).toBe(item.value);
+ expect(formatNumber).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/plugins/indicator/index.ts b/src/plugins/indicator/index.ts
index fe8f2f4c..2dbb38bc 100644
--- a/src/plugins/indicator/index.ts
+++ b/src/plugins/indicator/index.ts
@@ -2,7 +2,7 @@ import React from 'react';
import {ChartKitPlugin} from '../../types';
-export * from './types';
+export type {IndicatorWidgetData, IndicatorWidgetDataItem} from './public-types';
export const IndicatorPlugin: ChartKitPlugin = {
type: 'indicator',
diff --git a/src/plugins/indicator/normalize.ts b/src/plugins/indicator/normalize.ts
new file mode 100644
index 00000000..2f32fcde
--- /dev/null
+++ b/src/plugins/indicator/normalize.ts
@@ -0,0 +1,77 @@
+import type {
+ IndicatorFormatOptions,
+ IndicatorWidgetConfig,
+ IndicatorWidgetConfigItem,
+ NormalizedIndicatorWidgetConfig,
+ NormalizedIndicatorWidgetConfigItem,
+} from './types';
+
+/** Return the original formatNumber options, preserving application metadata and object identity. */
+export function getValueFormatOptions(item: IndicatorWidgetConfigItem): IndicatorFormatOptions {
+ if (item.value) {
+ return item.value;
+ }
+ if (item.content) {
+ return item.content.current;
+ }
+ throw new TypeError('An indicator item requires value or content.current.');
+}
+
+function normalizeValue(
+ item: IndicatorWidgetConfigItem,
+): NormalizedIndicatorWidgetConfigItem['value'] {
+ const value = getValueFormatOptions(item);
+ if (item.value) {
+ if (value.color === undefined && item.color !== undefined) {
+ const {value: rawValue, formatNumber, numberFormat, ...rest} = item.value;
+ return {...rest, value: rawValue, formatNumber, numberFormat, color: item.color};
+ }
+ return value;
+ }
+ if (
+ !('color' in value) &&
+ !('formatNumber' in value) &&
+ !('numberFormat' in value) &&
+ item.color === undefined
+ ) {
+ return value;
+ }
+ const {
+ value: rawValue,
+ color: _color,
+ formatNumber: _formatNumber,
+ numberFormat: _numberFormat,
+ ...rest
+ } = value;
+ return item.color === undefined
+ ? {...rest, value: rawValue}
+ : {...rest, value: rawValue, color: item.color};
+}
+
+/**
+ * Normalize indicator configuration without mutating input, invoking callbacks or logging.
+ */
+export function normalizeIndicatorData(
+ input: IndicatorWidgetConfig,
+): NormalizedIndicatorWidgetConfig {
+ const data = input.data?.map((item): NormalizedIndicatorWidgetConfigItem => {
+ const value = normalizeValue(item);
+
+ if (item.value === value && !('content' in item) && !('color' in item)) {
+ return item as NormalizedIndicatorWidgetConfigItem;
+ }
+
+ return {
+ value,
+ ...(item.secondaryValue ? {secondaryValue: item.secondaryValue} : {}),
+ ...(item.title === undefined ? {} : {title: item.title}),
+ ...(item.size === undefined ? {} : {size: item.size}),
+ ...(item.nowrap === undefined ? {} : {nowrap: item.nowrap}),
+ };
+ });
+
+ if (data?.every((item, index) => item === input.data?.[index]) ?? true) {
+ return input as NormalizedIndicatorWidgetConfig;
+ }
+ return {...input, data};
+}
diff --git a/src/plugins/indicator/public-types.ts b/src/plugins/indicator/public-types.ts
new file mode 100644
index 00000000..ba9307db
--- /dev/null
+++ b/src/plugins/indicator/public-types.ts
@@ -0,0 +1,54 @@
+import type {ReactNode} from 'react';
+
+import type {FormatNumberOptions} from '../shared';
+
+type IndicatorValue = {
+ /** Numbers can be formatted; strings are displayed as supplied. */
+ value: number | string;
+ /** Custom formatter; takes precedence over numberFormat. */
+ formatNumber?: (value: number) => string;
+ /** Explicit options take precedence over the widget's formatNumber callback. */
+ numberFormat?: Omit;
+ /** Any CSS color, including theme variables. */
+ color?: string;
+};
+
+type IndicatorItemOptions = {
+ size?: 's' | 'm' | 'l' | 'xl';
+ title?: string;
+ nowrap?: boolean;
+};
+
+type IndicatorSecondaryValue = IndicatorValue & {
+ caption?: ReactNode;
+ /** Defaults to bottom. */
+ position?: 'bottom' | 'right';
+ /** The label view uses a background derived from color. Defaults to text. */
+ view?: 'text' | 'label';
+ /** Hidden by default. */
+ arrow?: {
+ direction: 'up' | 'down';
+ /** Localized accessible label, for example "Increase". Omit for a decorative arrow. */
+ ariaLabel?: string;
+ };
+};
+
+type LegacyIndicatorContent = {
+ /** @deprecated Use value. */
+ current: {value: string | number} & Record;
+};
+
+export type IndicatorWidgetDataItem = IndicatorItemOptions & {
+ /** @deprecated Use value in ChartKitProps<'indicator'>['data']. */
+ content: LegacyIndicatorContent;
+ value?: IndicatorValue;
+ /** @deprecated Use value.color. */
+ color?: string;
+ secondaryValue?: IndicatorSecondaryValue;
+};
+
+export type IndicatorWidgetData = {
+ data?: IndicatorWidgetDataItem[];
+ /** Fallback color for primary values only. */
+ defaultColor?: string;
+};
diff --git a/src/plugins/indicator/renderer/IndicatorItem.tsx b/src/plugins/indicator/renderer/IndicatorItem.tsx
index 8f575451..e1569574 100644
--- a/src/plugins/indicator/renderer/IndicatorItem.tsx
+++ b/src/plugins/indicator/renderer/IndicatorItem.tsx
@@ -1,26 +1,22 @@
import React from 'react';
-import type {ChartKitProps} from '../../../types';
import {block} from '../../../utils/cn';
-import type {IndicatorWidgetDataItem} from '../types';
+import type {IndicatorItemProps} from '../types';
-const b = block('indicator');
+import {IndicatorSecondaryValue} from './IndicatorSecondaryValue';
-export const IndicatorItem = (
- props: IndicatorWidgetDataItem & {
- defaultColor?: string;
- formatNumber?: ChartKitProps<'indicator'>['formatNumber'];
- },
-) => {
- const {formatNumber, content, color, defaultColor, size, title, nowrap} = props;
- const mods = {size, nowrap};
- const style: React.CSSProperties = {color: color || defaultColor};
+const b = block('indicator');
- let value = content.current.value;
+export const IndicatorItem = (props: IndicatorItemProps) => {
+ const {value, size, title, nowrap, secondaryValue} = props;
+ const mods = {size, nowrap, right: secondaryValue?.position === 'right'};
+ const style: React.CSSProperties = {color: value.color};
- if (formatNumber && typeof value === 'number') {
- value = formatNumber(value, content.current);
- }
+ const valueContent = (
+
+ {value.value}
+
+ );
return (
@@ -29,9 +25,14 @@ export const IndicatorItem = (
{title}
)}
-
- {value}
-
+ {secondaryValue ? (
+
+ {valueContent}
+
+
+ ) : (
+ valueContent
+ )}
);
};
diff --git a/src/plugins/indicator/renderer/IndicatorSecondaryValue.tsx b/src/plugins/indicator/renderer/IndicatorSecondaryValue.tsx
new file mode 100644
index 00000000..a3fb1485
--- /dev/null
+++ b/src/plugins/indicator/renderer/IndicatorSecondaryValue.tsx
@@ -0,0 +1,63 @@
+import React from 'react';
+
+import {ArrowDown as ArrowDownIcon, ArrowUp as ArrowUpIcon} from '@gravity-ui/icons';
+import {Icon, Label} from '@gravity-ui/uikit';
+
+import {block} from '../../../utils/cn';
+import type {IndicatorItemProps} from '../types';
+
+const b = block('indicator');
+
+const LABEL_SIZE_BY_INDICATOR_SIZE = {s: 'xs', m: 's', l: 's', xl: 'm'} as const;
+const ICON_SIZE_BY_INDICATOR_SIZE = {s: 12, m: 14, l: 14, xl: 16} as const;
+
+export function IndicatorSecondaryValue({
+ secondaryValue,
+ size,
+}: {
+ secondaryValue: NonNullable;
+ size: IndicatorItemProps['size'];
+}) {
+ const {value, caption, view = 'text', arrow, color} = secondaryValue;
+ const labelSize = LABEL_SIZE_BY_INDICATOR_SIZE[size ?? 'm'];
+ const arrowIcon = arrow && (
+
+
+
+ );
+
+ return (
+
+
+ {view === 'label' ? (
+
+ ) : (
+
+ {arrowIcon}
+ {value}
+
+ )}
+ {caption !== null && caption !== undefined && caption !== '' && (
+
+ {caption}
+
+ )}
+
+
+ );
+}
diff --git a/src/plugins/indicator/renderer/IndicatorWidget.scss b/src/plugins/indicator/renderer/IndicatorWidget.scss
index 887c519c..72097a45 100644
--- a/src/plugins/indicator/renderer/IndicatorWidget.scss
+++ b/src/plugins/indicator/renderer/IndicatorWidget.scss
@@ -63,4 +63,82 @@
font-size: 48px;
white-space: nowrap;
}
+
+ &__value-row {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: var(--g-spacing-2);
+ }
+
+ &__item_right &__value-row {
+ flex-direction: row;
+ align-items: baseline;
+ gap: var(--g-spacing-3);
+ }
+
+ &__item_right &__secondary-value_view_label {
+ contain: layout;
+ }
+
+ &__secondary-value {
+ font-size: var(--g-text-body-1-font-size);
+ line-height: var(--g-text-body-1-line-height);
+ font-weight: var(--g-text-body-font-weight);
+ display: block;
+ min-width: min-content;
+ max-width: 100%;
+ }
+
+ &__secondary-value-content {
+ display: grid;
+ grid-auto-flow: column;
+ grid-template-columns: max-content;
+ grid-auto-columns: minmax(1em, 1fr);
+ align-items: center;
+ gap: calc(var(--g-spacing-1) + var(--g-spacing-half));
+ min-width: 0;
+ }
+
+ &__item_size_l &__secondary-value,
+ &__item_size_xl &__secondary-value {
+ font-size: var(--g-text-body-2-font-size);
+ line-height: var(--g-text-body-2-line-height);
+ }
+
+ &__secondary-value-text {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--g-spacing-half);
+ flex-shrink: 0;
+ font: inherit;
+ white-space: nowrap;
+ color: var(--g-color-text-primary);
+ }
+
+ &__secondary-value-arrow {
+ display: inline-flex;
+ flex-shrink: 0;
+ }
+
+ &__secondary-value-label {
+ color: var(--indicator-secondary-value-color, var(--g-color-text-primary));
+ background-color: color-mix(
+ in sRGB,
+ var(--indicator-secondary-value-color, var(--g-color-text-primary)) 15%,
+ transparent
+ );
+ }
+
+ &__secondary-value-caption {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--g-color-text-secondary);
+
+ &:empty {
+ display: none;
+ }
+ }
}
diff --git a/src/plugins/indicator/renderer/IndicatorWidget.tsx b/src/plugins/indicator/renderer/IndicatorWidget.tsx
index ff679eb4..485d24a9 100644
--- a/src/plugins/indicator/renderer/IndicatorWidget.tsx
+++ b/src/plugins/indicator/renderer/IndicatorWidget.tsx
@@ -8,24 +8,25 @@ import {CHARTKIT_ERROR_CODE, ChartKitError} from '../../../libs';
import type {ChartKitProps, ChartKitWidgetRef} from '../../../types';
import {getChartPerformanceDuration, getRandomCKId, markChartPerformance} from '../../../utils';
import {block} from '../../../utils/cn';
+import {getValueFormatOptions, normalizeIndicatorData} from '../normalize';
+import type {IndicatorItemProps} from '../types';
import {IndicatorItem} from './IndicatorItem';
+import {formatValue} from './utils';
import './IndicatorWidget.scss';
const b = block('indicator');
const IndicatorWidget = React.forwardRef>(
- // _ref needs to avoid this React warning:
- // "forwardRef render functions accept exactly two parameters: props and ref"
function IndicatorWidgetInner(props, _ref) {
- const {
- onLoad,
- formatNumber,
- data: {data = [], defaultColor},
- id,
- onRender,
- } = props;
+ const {onLoad, formatNumber, data: config, id, onRender} = props;
+ const {data = [], defaultColor} = config;
+
+ const normalizedData = React.useMemo(
+ () => normalizeIndicatorData(config).data ?? [],
+ [config],
+ );
const generatedId = React.useMemo(
() => `${id}_${getRandomCKId()}`,
@@ -49,16 +50,34 @@ const IndicatorWidget = React.forwardRef {
+ const {value, secondaryValue, title, size, nowrap} = item;
+ return {
+ title,
+ size,
+ nowrap,
+ value: {
+ value: formatValue(value, formatNumber, getValueFormatOptions(data[index])),
+ color: value.color || defaultColor,
+ },
+ secondaryValue: secondaryValue
+ ? {
+ value: formatValue(secondaryValue),
+ color: secondaryValue.color,
+ caption: secondaryValue.caption,
+ position: secondaryValue.position,
+ view: secondaryValue.view,
+ arrow: secondaryValue.arrow,
+ }
+ : undefined,
+ };
+ });
+
return (
- {data.map((item, index) => (
-
+ {items.map((item, index) => (
+
))}
diff --git a/src/plugins/indicator/renderer/__tests__/utils.test.ts b/src/plugins/indicator/renderer/__tests__/utils.test.ts
new file mode 100644
index 00000000..55134470
--- /dev/null
+++ b/src/plugins/indicator/renderer/__tests__/utils.test.ts
@@ -0,0 +1,93 @@
+import {settings} from '../../../../libs';
+import {formatValue} from '../utils';
+
+describe('formatValue', () => {
+ afterEach(() => settings.set({lang: 'en'}));
+
+ test('prefers a local callback over options and the widget callback', () => {
+ const localFormatNumber = vi.fn(() => 'local');
+ const formatNumber = vi.fn(() => 'widget');
+ expect(
+ formatValue(
+ {
+ value: 0.124,
+ formatNumber: localFormatNumber,
+ numberFormat: {format: 'percent', precision: 1},
+ },
+ formatNumber,
+ ),
+ ).toBe('local');
+ expect(localFormatNumber).toHaveBeenCalledExactlyOnceWith(0.124);
+ expect(formatNumber).not.toHaveBeenCalled();
+ });
+
+ test('selects explicit formats, then the callback, then plain text', () => {
+ const formatNumber = vi.fn(() => 'custom');
+ expect(
+ formatValue(
+ {
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1, signDisplay: 'exceptZero'},
+ },
+ formatNumber,
+ ),
+ ).toBe('+12.4%');
+ expect(formatValue({value: 1200, numberFormat: {}}, formatNumber)).toBe('1,200');
+ expect(formatNumber).not.toHaveBeenCalled();
+ expect(formatValue({value: 1200}, formatNumber)).toBe('custom');
+ expect(formatNumber).toHaveBeenCalledExactlyOnceWith(1200, {value: 1200});
+ expect(formatValue({value: 1234.5})).toBe('1234.5');
+ });
+
+ test('applies a multiplier and an explicit scale', () => {
+ expect(
+ formatValue({
+ value: 1.5,
+ numberFormat: {multiplier: 1000, unit: 'm', unitRate: 1},
+ }),
+ ).toBe('1.5K');
+ });
+
+ test('preserves numeric strings without invoking formatters', () => {
+ const localFormatNumber = vi.fn();
+ const formatNumber = vi.fn();
+ expect(
+ formatValue(
+ {
+ value: '0.124',
+ formatNumber: localFormatNumber,
+ numberFormat: {format: 'percent', precision: 1},
+ },
+ formatNumber,
+ ),
+ ).toBe('0.124');
+ expect(localFormatNumber).not.toHaveBeenCalled();
+ expect(formatNumber).not.toHaveBeenCalled();
+ });
+
+ test('uses the widget locale unless the value overrides it', () => {
+ settings.set({lang: 'ru'});
+ expect(
+ formatValue({
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1},
+ }),
+ ).toBe('12,4%');
+ expect(
+ formatValue({
+ value: 0.124,
+ numberFormat: {format: 'percent', precision: 1, lang: 'en'},
+ }),
+ ).toBe('12.4%');
+ });
+
+ test('supports regional locales and rounds decimal ties in explicit formats', () => {
+ expect(formatValue({value: 1200, numberFormat: {lang: 'en-US'}})).toBe('1,200');
+ expect(
+ formatValue({
+ value: 0.01005,
+ numberFormat: {lang: 'ru-RU', format: 'percent', precision: 2},
+ }),
+ ).toBe('1,01%');
+ });
+});
diff --git a/src/plugins/indicator/renderer/utils.ts b/src/plugins/indicator/renderer/utils.ts
new file mode 100644
index 00000000..1380fde9
--- /dev/null
+++ b/src/plugins/indicator/renderer/utils.ts
@@ -0,0 +1,37 @@
+import {settings} from '../../../libs';
+import {formatNumber as defaultFormatNumber} from '../../shared';
+import type {IndicatorFormatOptions, NormalizedIndicatorWidgetConfigItem} from '../types';
+
+export function formatValue(
+ {
+ value,
+ formatNumber: localFormatNumber,
+ numberFormat,
+ }: Pick<
+ NormalizedIndicatorWidgetConfigItem['value'],
+ 'value' | 'formatNumber' | 'numberFormat'
+ >,
+ formatNumber?: (value: number, options: {value: number | string}) => string,
+ formatOptions?: IndicatorFormatOptions,
+): string {
+ if (typeof value === 'string') {
+ return value;
+ }
+
+ if (localFormatNumber) {
+ return localFormatNumber(value);
+ }
+
+ if (numberFormat) {
+ return defaultFormatNumber(value, {
+ ...numberFormat,
+ lang: numberFormat.lang ?? settings.get('lang'),
+ });
+ }
+
+ if (formatNumber) {
+ return formatNumber(value, formatOptions ?? {value});
+ }
+
+ return String(value);
+}
diff --git a/src/plugins/indicator/types.ts b/src/plugins/indicator/types.ts
index ac7caad4..9df57b80 100644
--- a/src/plugins/indicator/types.ts
+++ b/src/plugins/indicator/types.ts
@@ -1,16 +1,47 @@
-export type IndicatorWidgetDataItem = {
- content: {
- current: {
- value: string | number;
- } & Record;
- };
- color?: string;
- size?: 's' | 'm' | 'l' | 'xl';
- title?: string;
- nowrap?: boolean;
+import type {IndicatorWidgetData, IndicatorWidgetDataItem} from './public-types';
+
+/**
+ * Indicator item before normalization, using either value or legacy content.current.
+ * When both are provided, value takes precedence.
+ */
+export type IndicatorWidgetConfigItem =
+ | IndicatorWidgetDataItem
+ | (Omit & {
+ value: NonNullable;
+ content?: IndicatorWidgetDataItem['content'];
+ });
+
+/** Indicator configuration accepted by the widget before normalization. */
+export type IndicatorWidgetConfig = Omit & {
+ data?: IndicatorWidgetConfigItem[];
};
-export type IndicatorWidgetData = {
- data?: IndicatorWidgetDataItem[];
- defaultColor?: string;
+/** Original primary value object passed to the widget's formatNumber callback, including application metadata. */
+export type IndicatorFormatOptions = {value: string | number} & Record;
+
+/** Indicator item after normalization, with a required value and no legacy content or item-level color. */
+export type NormalizedIndicatorWidgetConfigItem = Omit<
+ IndicatorWidgetConfigItem,
+ 'content' | 'color' | 'value'
+> & {
+ value: NonNullable;
+};
+
+/** Indicator configuration with normalized items, ready for formatting. */
+export type NormalizedIndicatorWidgetConfig = Omit & {
+ data?: NormalizedIndicatorWidgetConfigItem[];
+};
+
+/** Rendering props with primary and secondary values formatted as strings. */
+export type IndicatorItemProps = Pick<
+ NormalizedIndicatorWidgetConfigItem,
+ 'title' | 'size' | 'nowrap'
+> & {
+ value: Pick & {
+ value: string;
+ };
+ secondaryValue?: Omit<
+ NonNullable,
+ 'value' | 'formatNumber' | 'numberFormat'
+ > & {value: string};
};
diff --git a/src/plugins/shared/format-number/format-number.test.ts b/src/plugins/shared/format-number/format-number.test.ts
index bbbaea9b..c0d42909 100644
--- a/src/plugins/shared/format-number/format-number.test.ts
+++ b/src/plugins/shared/format-number/format-number.test.ts
@@ -1,4 +1,4 @@
-import {formatNumber} from './format-number';
+import {formatBytes, formatDuration, formatNumber} from './format-number';
import {i18nInstance} from './i18n/i18n';
import type {FormatNumberOptions} from './types';
@@ -10,8 +10,49 @@ describe('plugins/shared', () => {
[NaN, undefined, 'NaN'],
['0.2211556', undefined, '0.2211556'],
['0.2211556', {precision: 4}, '0.2212'],
+ [1.005, {precision: 2}, '1.01'],
+ [2.675, {precision: 2}, '2.68'],
+ [-1.005, {precision: 2}, '-1.01'],
+ [0.01005, {format: 'percent', precision: 2}, '1.01%'],
+ [0.145, {format: 'percent', precision: 0}, '15%'],
+ [-0.145, {format: 'percent', precision: 0}, '-15%'],
+ [0.285, {format: 'percent', precision: 0, lang: 'ru-RU'}, '29%'],
+ [1.005, {format: 'percent', precision: 0}, '101%'],
+ [12.345, {format: 'percent', unit: 'auto', precision: 2}, '1.23K%'],
+ [0.0001245, {format: 'percent', precision: 'auto'}, '0.0125%'],
+ [1005, {unit: 'k', precision: 2}, '1.01K'],
+ [1.005, {precision: 'auto'}, '1.01'],
+ [0.12345, {precision: 'auto'}, '0.1235'],
+ [1200, {lang: 'en-US'}, '1,200'],
+ [1234567, {lang: 'en-US', unit: 'auto', precision: 1}, '1.2M'],
+ [1234567, {lang: 'ru-RU', unit: 'auto', precision: 1}, '1,2M'],
+ [1234567, {lang: 'de-DE', unit: 'auto', precision: 1}, '1,2M'],
+ [12.4, {signDisplay: 'exceptZero'}, '+12.4'],
+ [-12.4, {signDisplay: 'exceptZero'}, '-12.4'],
+ [0, {signDisplay: 'exceptZero'}, '0'],
+ [0, {signDisplay: 'always'}, '+0'],
+ [-12.4, {signDisplay: 'never'}, '12.4'],
+ [12.4, {signDisplay: 'auto'}, '12.4'],
+ [0.124, {format: 'percent', precision: 1, signDisplay: 'exceptZero'}, '+12.4%'],
+ [0.0004, {format: 'percent', precision: 1, signDisplay: 'exceptZero'}, '0.0%'],
+ [-0.0004, {format: 'percent', precision: 1, signDisplay: 'exceptZero'}, '0.0%'],
+ [12.4, {labelMode: 'percent'}, '12.4%'],
+ [0.124, {format: 'percent', multiplier: 10}, '12.4%'],
])('formatNumber (args: {value: %p, options: %p})', (value, options, expected) => {
const result = formatNumber(value as number, options);
expect(result).toEqual(expected);
});
+
+ test('localizes unit names independently of the number locale', () => {
+ expect(formatBytes(1536, {lang: 'ru-RU'})).toBe('1,5 КБ');
+ expect(formatBytes(1536, {lang: 'en-US'})).toBe('1.5 KB');
+ expect(formatBytes(1536, {lang: 'de-DE'})).toBe('1,5 KB');
+ expect(formatDuration(1500, {lang: 'ru-RU'})).toBe('1,5 с');
+ expect(i18nInstance.lang).toBe('en');
+ });
+
+ test('preserves the shared locale when formatting fails', () => {
+ expect(() => formatNumber(1.005, {lang: 'ru-RU', precision: -1})).toThrow(RangeError);
+ expect(i18nInstance.lang).toBe('en');
+ });
});
diff --git a/src/plugins/shared/format-number/format-number.ts b/src/plugins/shared/format-number/format-number.ts
index 187c854c..aef3988c 100644
--- a/src/plugins/shared/format-number/format-number.ts
+++ b/src/plugins/shared/format-number/format-number.ts
@@ -10,8 +10,7 @@ function getUnitRate(value: number, exponent: number, unitsI18nKeys: string[]) {
let resultUnitRate = 1;
while (
Math.abs(value / Math.pow(exponent, resultUnitRate)) >= 1 &&
- resultUnitRate < 10 &&
- i18n(unitsI18nKeys[resultUnitRate])
+ resultUnitRate < unitsI18nKeys.length
) {
resultUnitRate++;
}
@@ -28,36 +27,56 @@ const unitFormatter = ({
unitsI18nKeys: string[];
unitDelimiterI18nKey: string;
}) => {
- return function formatUnit(value: number, options: FormatOptions = {}) {
- const {precision, unitRate, showRankDelimiter = true, lang} = options;
-
- const i18nLang = i18nInstance.lang as string;
- if (lang) {
- i18nInstance.setLang(lang);
- }
+ return function formatUnit(
+ value: number,
+ options: FormatOptions = {},
+ format: 'number' | 'percent' = 'number',
+ ) {
+ const {precision, unitRate, showRankDelimiter = true, lang, signDisplay} = options;
+ const locale = lang ?? (i18nInstance.lang as string);
+ const isPercent = format === 'percent';
const resultUnitRate =
- typeof unitRate === 'number' ? unitRate : getUnitRate(value, exponent, unitsI18nKeys);
+ typeof unitRate === 'number'
+ ? unitRate
+ : getUnitRate(isPercent ? value * 100 : value, exponent, unitsI18nKeys);
- let result: number | string = value / Math.pow(exponent, resultUnitRate);
+ const scaledValue = value / Math.pow(exponent, resultUnitRate);
+ let maximumFractionDigits = 20;
if (typeof precision === 'number') {
- result = Number(result.toFixed(precision));
- } else if (precision === 'auto' && result % 1 !== 0) {
- result = Number(result.toFixed(Math.abs(result) > 1 ? 2 : 4));
+ maximumFractionDigits = precision;
+ } else if (precision === 'auto') {
+ maximumFractionDigits = Math.abs(scaledValue) > (isPercent ? 0.01 : 1) ? 2 : 4;
}
-
- result = new Intl.NumberFormat(lang ?? i18nLang, {
+ const formatter = new Intl.NumberFormat(locale, {
+ style: isPercent ? 'percent' : 'decimal',
minimumFractionDigits: typeof precision === 'number' ? precision : 0,
- maximumFractionDigits: 20,
+ maximumFractionDigits,
useGrouping: showRankDelimiter,
- }).format(result);
-
- const unit = i18n(unitsI18nKeys[resultUnitRate]);
- const delimiter = i18n(unitDelimiterI18nKey);
-
- i18nInstance.setLang(i18nLang);
-
- return `${result}${delimiter}${unit}`;
+ signDisplay,
+ });
+ const result = isPercent
+ ? formatter
+ .formatToParts(scaledValue)
+ .filter(
+ ({type, value: part}) =>
+ type !== 'percentSign' && (type !== 'literal' || part.trim() !== ''),
+ )
+ .map(({value: part}) => part)
+ .join('')
+ : formatter.format(scaledValue);
+
+ const unitsLang = new Intl.Locale(locale).language === 'ru' ? 'ru' : 'en';
+ const i18nLang = i18nInstance.lang as string;
+ i18nInstance.setLang(unitsLang);
+ try {
+ const unit = i18n(unitsI18nKeys[resultUnitRate]);
+ const delimiter = i18n(unitDelimiterI18nKey);
+
+ return `${result}${delimiter}${unit}`;
+ } finally {
+ i18nInstance.setLang(i18nLang);
+ }
};
};
@@ -118,7 +137,7 @@ export const formatNumber = (value: number | string, options: FormatNumberOption
let prePostfix = '';
if (format === 'percent') {
- changedMultiplier = 100;
+ changedMultiplier = 1;
prePostfix = '%';
}
@@ -126,10 +145,14 @@ export const formatNumber = (value: number | string, options: FormatNumberOption
prePostfix = '%';
}
- const formattedValue = baseFormatNumber(Number(value) * changedMultiplier, {
- ...options,
- unitRate: unitRate ?? NUMBER_UNIT_RATE_BY_UNIT[unit ?? 'default'],
- });
+ const formattedValue = baseFormatNumber(
+ Number(value) * changedMultiplier,
+ {
+ ...options,
+ unitRate: unitRate ?? NUMBER_UNIT_RATE_BY_UNIT[unit ?? 'default'],
+ },
+ format,
+ );
return `${prefix}${formattedValue}${prePostfix}${postfix}`;
};
diff --git a/src/plugins/shared/format-number/types.ts b/src/plugins/shared/format-number/types.ts
index 25f32fb4..cf28c9c5 100644
--- a/src/plugins/shared/format-number/types.ts
+++ b/src/plugins/shared/format-number/types.ts
@@ -2,6 +2,7 @@ export type FormatOptions = {
precision?: number | 'auto';
unitRate?: number;
showRankDelimiter?: boolean;
+ signDisplay?: Intl.NumberFormatOptions['signDisplay'];
lang?: string;
labelMode?: string;
};
diff --git a/src/types/index.ts b/src/types/index.ts
index 6aeff40f..de3c1d51 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,6 +1,7 @@
import React from 'react';
import {ChartKitError} from '../libs';
+import type {IndicatorWidgetConfig} from '../plugins/indicator/types';
import type {ChartKitWidget} from './widget';
@@ -45,7 +46,7 @@ export type ChartKitRenderPluginLoader = () => React.ReactNode;
export type ChartKitProps = {
type: T;
- data: ChartKitWidget[T]['data'];
+ data: ChartKitWidget[T]['data'] | (T extends 'indicator' ? IndicatorWidgetConfig : never);
id?: string;
isMobile?: boolean;
onLoad?: (data?: ChartKitOnLoadData) => void;
diff --git a/src/types/widget.ts b/src/types/widget.ts
index 6db15806..ec62fdcf 100644
--- a/src/types/widget.ts
+++ b/src/types/widget.ts
@@ -2,7 +2,7 @@ import type {ChartData} from '@gravity-ui/charts';
import type {SplitLayoutType} from '../components/SplitPane/types';
import type {Highcharts, HighchartsWidgetData, StringParams} from '../plugins/highcharts/types';
-import type {IndicatorWidgetData} from '../plugins/indicator/types';
+import type {IndicatorWidgetData} from '../plugins/indicator/public-types';
import type {CustomTooltipProps, Yagr, YagrWidgetData} from '../plugins/yagr/types';
export interface ChartKitWidget {
diff --git a/test-utils/tester.html b/test-utils/tester.html
new file mode 100644
index 00000000..9d1e2968
--- /dev/null
+++ b/test-utils/tester.html
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+ ChartKit browser tests
+
+
+
+
diff --git a/vitest.config.ts b/vitest.config.ts
index 28ca981a..3d0fe88c 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -16,6 +16,7 @@ export default defineConfig({
},
browser: {
enabled: true,
+ testerHtmlPath: 'test-utils/tester.html',
headless: true,
provider: playwright({}),
instances: [
@@ -95,6 +96,9 @@ export default defineConfig({
{
extends: true,
plugins: [react()],
+ optimizeDeps: {
+ include: ['@gravity-ui/icons'],
+ },
test: {
name: 'visual',
include: ['src/**/*.visual.test.ts?(x)'],