diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 78fe9d4a..5e498ebd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,3 +94,5 @@ jobs: run: npm ci - name: Build run: npm run build + - name: Check Build + run: npm run test:build diff --git a/.storybook/preview-head.html b/.storybook/preview-head.html new file mode 100644 index 00000000..fea6dc98 --- /dev/null +++ b/.storybook/preview-head.html @@ -0,0 +1,4 @@ + diff --git a/docs/indicator.md b/docs/indicator.md new file mode 100644 index 00000000..65cdc4c7 --- /dev/null +++ b/docs/indicator.md @@ -0,0 +1,187 @@ +# Indicator + +The indicator displays one or more values with optional titles. + +Register `IndicatorPlugin` from `@gravity-ui/chartkit/indicator` and pass the +configuration to ``: + +```tsx +import ChartKit, {settings, type ChartKitProps} from '@gravity-ui/chartkit'; +import {IndicatorPlugin} from '@gravity-ui/chartkit/indicator'; + +settings.set({plugins: [IndicatorPlugin]}); + +const data: ChartKitProps<'indicator'>['data'] = { + data: [ + { + title: 'Revenue', + value: { + value: 1539577, + numberFormat: {precision: 0, showRankDelimiter: true}, + }, + size: 'm', + secondaryValue: { + value: 0.124, + numberFormat: { + format: 'percent', + precision: 1, + signDisplay: 'exceptZero', + }, + caption: 'vs the previous month', + position: 'right', + color: 'var(--g-color-text-positive)', + view: 'label', + arrow: {direction: 'up', ariaLabel: 'Increase'}, + }, + }, + ], +}; + +; +``` + +With the English locale, this example displays `1,539,577` as the main value and +`+12.4%` as the secondary value. Strings render as supplied, including strings that look like numbers. +The application computes differences, chooses colors and localizes captions. + +## Configuration + +The widget configuration contains a `data` array with one entry per indicator. +Use `ChartKitProps<'indicator'>['data']` for configurations with `value` +or a mix of new and legacy items. Use `ChartKitProps<'indicator'>` for the props +of a wrapper around ``. + +`IndicatorWidgetData` and `IndicatorWidgetDataItem` retain the legacy contract +with required `content.current`, so existing TypeScript wrappers and interfaces +can keep using them. + +| Item property | Description | Default | +| ---------------- | ------------------------------------------------------------------------- | ------------------------------------- | +| `value` | Main value | Required unless using the legacy form | +| `secondaryValue` | Additional value | None | +| `title` | Text displayed above the main value | None | +| `size` | `s`, `m`, `l`, or `xl`; controls both values | `m` | +| `nowrap` | Truncate the title to one line and show its full text in a native tooltip | `false` | + +Both values accept `value`, `formatNumber`, `numberFormat`, and `color`. + +Set the widget's `defaultColor` to provide a fallback color for primary values. +`value.color` overrides it. Secondary values have their own `color`. + +## Secondary value + +| Secondary value property | Description | Default | +| ------------------------ | -------------------------------------------------------------------------------- | ------------------ | +| `value` | A number or an already formatted string | Required | +| `formatNumber` | A custom `(value: number) => string` formatter; overrides `numberFormat` | None | +| `numberFormat` | Formatting options applied to this value | None | +| `caption` | A caption (`ReactNode`); string captions also have a native tooltip | None | +| `position` | `bottom` or `right` | `bottom` | +| `color` | A CSS color for the value and arrow, including theme variables | Primary text color | +| `view` | `text` or `label`; the label background is a 15% tint of `color` | `text` | +| `arrow.direction` | `up` or `down`, chosen explicitly by the application | None | +| `arrow.ariaLabel` | A localized accessible label for the arrow, for example `Increase` or `Decrease` | None | + +Provide `arrow.ariaLabel` when the arrow conveys information beyond the displayed +value. The application localizes this label. Without a label, the arrow is +decorative, so its meaning should be conveyed by the value or caption as well. + +## Number formatting + +Set `value.numberFormat` for the main value and +`secondaryValue.numberFormat` for the secondary value. The two configurations are +independent and accept the following options: + +| Option | Description | Default | +| ------------------- | ------------------------------------------------------------------------------------------ | -------------------- | +| `format` | `number` or `percent`; percent multiplies the value by 100 | `number` | +| `precision` | Fraction digits, or `auto` for adaptive precision | No fixed precision | +| `showRankDelimiter` | Group thousands | `true` | +| `unit` | `auto`, `k`, `m`, `b`, `t`, or `null` for no scaling | No scaling | +| `unitRate` | Scale index: `0` for units, `1` for thousands, through `4` for trillions; overrides `unit` | Determined by `unit` | +| `multiplier` | Multiply the number before formatting | `1` | +| `prefix` | Text prepended to the formatted value | Empty string | +| `postfix` | Text appended to the formatted value | Empty string | +| `lang` | Locale override | `settings.lang` | +| `signDisplay` | `auto`, `always`, `never` or `exceptZero` | `auto` | + +`lang` accepts an `Intl.NumberFormat` locale, including regional tags such as +`en-US` and `ru-RU`. Unit labels use Russian for `ru` locales and English otherwise. + +With `format: 'percent'`, the multiplier is always `100`; a supplied `multiplier` +is ignored. + +For the numeric main value, formatting priority is: + +1. The local `value.formatNumber` callback. +2. Explicit `value.numberFormat` options, applied by ChartKit's built-in formatter. +3. The widget's `formatNumber` callback. It receives the number and the complete + `value` object, or the legacy `content.current` object including application metadata. +4. Plain text if no callback or options are supplied. + +For the numeric secondary value, formatting priority is: + +1. The local `secondaryValue.formatNumber` callback. +2. Explicit `secondaryValue.numberFormat` options. +3. Plain text if no callback or options are supplied. + +Local callbacks receive the number and return its display string, including any +sign or unit. The widget's callback applies only to main values; it can serve as +a shared default for multiple indicators. Each value can independently provide +a local callback or options: + +```ts +const data: ChartKitProps<'indicator'>['data'] = { + data: [ + { + value: {value: 1200, formatNumber: (value) => `${value} USD`}, + secondaryValue: { + value: 0.124, + numberFormat: {format: 'percent', precision: 1}, + }, + }, + ], +}; +``` + +An empty `numberFormat` object `{}` selects the built-in defaults and overrides +the widget's callback. The built-in formatter uses `settings.lang` unless +`numberFormat.lang` is specified. Strings bypass all formatters. To display a +missing value, supply a string such as `value: '—'` and omit `arrow`. + +`numberFormat.signDisplay` follows `Intl.NumberFormat` semantics: `auto`, `always`, +`never` or `exceptZero`. For example, `exceptZero` shows a plus sign for positive +values and omits the sign for values rounded to zero. + +## Legacy configuration + +The legacy form supplies the main value through `content.current.value` and its +color through the item-level `color` property: + +```tsx +import type {IndicatorWidgetData} from '@gravity-ui/chartkit/indicator'; + +const data: IndicatorWidgetData = { + data: [ + { + title: 'Revenue', + content: {current: {value: 1539577}}, + color: 'var(--g-color-text-positive)', + }, + ], +}; + + value.toLocaleString('en-US')} />; +``` + +The item also accepts `title`, `size`, `nowrap`, and `secondaryValue` as described +above. The widget's `defaultColor` is used when the item has no color. + +For a numeric main value, `formatNumber` receives the number and the complete +`content.current` object, including application metadata. Fields inside +`content.current` other than `value`, including `color`, `formatNumber`, and `numberFormat`, are +formatter metadata and do not configure the display. Strings render as supplied. + +When an item supplies both forms, `value` determines the main value. +If `value.color` is omitted, the item-level `color` is used. An explicitly +empty `value.color` uses `defaultColor`. diff --git a/package-lock.json b/package-lock.json index f4441795..5c8662f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@gravity-ui/charts": "^1.73.1", "@gravity-ui/date-utils": "^2.1.0", "@gravity-ui/i18n": "^1.0.0", + "@gravity-ui/icons": "^2.23.1", "@gravity-ui/yagr": "^5.0.0", "afterframe": "^1.0.2", "lodash": "^4.17.21", @@ -1603,9 +1604,9 @@ "integrity": "sha512-jZotOX73lMVARsNZ5L8rquDhyCIcHnX7GwT32m6vrnqy6iKBfBdOuAnAalUbnoVJoasfvYiSyX3kwusetyZgfQ==" }, "node_modules/@gravity-ui/icons": { - "version": "2.16.0", - "resolved": "https://registry.npmjs.org/@gravity-ui/icons/-/icons-2.16.0.tgz", - "integrity": "sha512-AMjPSO+7yPpvcCa9k+ZFNOZ+8cmIauLyRMswhoyfQ7SeoJOVzsAa2OP/B+Dd+AZRvzTaeJha4m2iEk93JvAklA==", + "version": "2.23.1", + "resolved": "https://registry.npmjs.org/@gravity-ui/icons/-/icons-2.23.1.tgz", + "integrity": "sha512-sinT5jSWuP0KCYPJVsl4PiTnZUNQ3h4BgPazdcVf/nTNlZhsbDivfuLFSqCt5dC/Tn3NzhrTWJXqhlBQtF710Q==", "license": "MIT", "dependencies": { "tslib": "^2.8.1" diff --git a/package.json b/package.json index 26cae29c..1e087ec3 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "@gravity-ui/charts": "^1.73.1", "@gravity-ui/date-utils": "^2.1.0", "@gravity-ui/i18n": "^1.0.0", + "@gravity-ui/icons": "^2.23.1", "@gravity-ui/yagr": "^5.0.0", "afterframe": "^1.0.2", "lodash": "^4.17.21", @@ -129,6 +130,7 @@ "test:coverage": "vitest run --project unit --coverage", "test:storybook": "vitest run --project storybook", "test:unit": "vitest run --project unit", + "test:build": "node scripts/check-build.mjs", "test:visual": "vitest run --project visual", "test:docker": "./scripts/playwright-docker.sh npm run test:visual --", "test:docker:update": "./scripts/playwright-docker.sh npm run test:visual -- --update", diff --git a/scripts/check-build.mjs b/scripts/check-build.mjs new file mode 100644 index 00000000..9204d584 --- /dev/null +++ b/scripts/check-build.mjs @@ -0,0 +1,169 @@ +#!/usr/bin/env node +// Run after npm run build. Check the published v8 declarations with bundler and legacy +// node resolution, including the legacy indicator contract and the new value configuration. +import {spawnSync} from 'node:child_process'; +import {mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync} from 'node:fs'; +import {createRequire} from 'node:module'; +import {tmpdir} from 'node:os'; +import {dirname, join, resolve} from 'node:path'; +import {execPath, exit, stderr, stdout} from 'node:process'; + +const ROOT = resolve(import.meta.dirname, '..'); +const {name} = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')); +const require = createRequire(import.meta.url); +let failed = false; + +const CONSUMER_BASE = `import ChartKit, {settings} from '${name}'; +import type {ChartKitProps, ChartKitWidget} from '${name}'; +import {GravityChartsPlugin} from '${name}/gravity-charts'; +import {HighchartsPlugin} from '${name}/highcharts'; +import type {HighchartsWidgetData} from '${name}/highcharts'; +import {IndicatorPlugin} from '${name}/indicator'; +import type {IndicatorWidgetData, IndicatorWidgetDataItem} from '${name}/indicator'; +import {YagrPlugin} from '${name}/yagr'; + +settings.set({plugins: [GravityChartsPlugin, HighchartsPlugin, IndicatorPlugin, YagrPlugin]}); + +interface AppIndicator extends IndicatorWidgetDataItem {appId: string} +interface AppIndicatorData extends IndicatorWidgetData {appId: string} +type LegacyCurrent = IndicatorWidgetDataItem['content']['current']; +function readLegacyIndicator(item: IndicatorWidgetDataItem): string | number { + const current: LegacyCurrent = item.content.current; + return current.value; +} +function readLegacyWidget(data: ChartKitWidget['indicator']['data']): string | number | undefined { + return data.data?.[0].content.current.value; +} +function forwardLegacyData(data: ChartKitWidget[T]['data']): ChartKitProps['data'] { + return data; +} +const legacyIndicator: IndicatorWidgetDataItem = {content: {current: {value: 42, numberFormat: 'application metadata', formatNumber: 'application metadata', customMetadata: 'legacy'}}}; +const legacyIndicatorValue: string | number = legacyIndicator.content.current.value; +const legacyIndicatorData: IndicatorWidgetData = {data: [legacyIndicator]}; +ChartKit({type: 'indicator', data: legacyIndicatorData}); +type IndicatorInput = ChartKitProps<'indicator'>['data']; +type IndicatorInputItem = NonNullable[number]; +const numberFormat = {unitRate: 1, multiplier: 1000, precision: 1}; +const indicatorData: IndicatorInput = {data: [{value: {value: 42, numberFormat}, secondaryValue: {value: 1, arrow: {direction: 'up', ariaLabel: 'Increase'}}}]}; +const indicatorWithCallbacks: IndicatorInput = {data: [{value: {value: 42, formatNumber: (value) => String(value), numberFormat}, secondaryValue: {value: 1, formatNumber: (value) => String(value), numberFormat}}]}; +ChartKit({type: 'indicator', data: indicatorWithCallbacks}); +const publicIndicatorData: ChartKitWidget['indicator']['data'] = legacyIndicatorData; +const indicatorInput: IndicatorInput = {data: [legacyIndicator, ...indicatorData.data!]}; +const indicatorProps: ChartKitProps<'indicator'> = {type: 'indicator', data: indicatorInput}; +ChartKit(indicatorProps); +ChartKit({type: 'indicator', data: indicatorData}); + +type TooltipLine = Parameters>[0]['lines'][number]; +const tooltipFormat: Pick = {chartKitFormat: 'number', chartKitPrecision: 'auto', chartKitUnit: 'k'}; +export {ChartKit}; +`; + +const CONSUMER_CHECKS = ` +// @ts-expect-error the normalized indicator configuration is internal +import type {NormalizedIndicatorWidgetConfig} from '${name}/indicator'; +// @ts-expect-error the shared value shape is internal +import type {IndicatorValue} from '${name}/indicator'; +// @ts-expect-error clean configuration types are internal +import type {IndicatorWidgetConfig} from '${name}/indicator'; +// @ts-expect-error clean configuration item types are internal +import type {IndicatorWidgetConfigItem} from '${name}/indicator'; +// @ts-expect-error standalone formatting types are internal +import type {FormatNumberOptions} from '${name}/indicator'; +// @ts-expect-error the indicator value type must not degrade to any +const invalidIndicator: IndicatorInput = {data: [{value: {value: false}}]}; +// @ts-expect-error the new value configuration does not accept arbitrary metadata +const invalidValueMetadata: IndicatorInput = {data: [{value: {value: 42, customMetadata: 'new'}}]}; +// @ts-expect-error the new value configuration must reject misspelled display options +const invalidValueColor: IndicatorInput = {data: [{value: {value: 42, colour: 'green'}}]}; +// @ts-expect-error local callbacks must return strings +const invalidValueCallback: IndicatorInput = {data: [{value: {value: 42, formatNumber: () => 42}}]}; +// @ts-expect-error secondary callbacks must return strings +const invalidSecondaryCallback: IndicatorInput = {data: [{value: {value: 42}, secondaryValue: {value: 1, formatNumber: () => 1}}]}; +// @ts-expect-error the legacy value type must retain its original contract +const invalidLegacyValue: IndicatorWidgetDataItem['content']['current']['value'] = false; +// @ts-expect-error the legacy item type must keep content required +const invalidLegacyItem: IndicatorWidgetDataItem = {value: {value: 42}}; +// @ts-expect-error each indicator requires value or content.current +const emptyIndicator: IndicatorInput = {data: [{}]}; +// @ts-expect-error the extended indicator input must not widen other plugins' data +const invalidHighchartsInput: ChartKitProps<'highcharts'>['data'] = indicatorData; +// @ts-expect-error arrows use an object with a direction +const invalidArrow: NonNullable = {value: 1, arrow: 'up'}; +// @ts-expect-error arrow directions are restricted to up and down +const invalidDirection: NonNullable = {value: 1, arrow: {direction: 'left'}}; +// @ts-expect-error labelMode is not an indicator formatting option +const invalidNumberFormat: IndicatorInputItem = {value: {value: 1, numberFormat: {labelMode: 'percent'}}}; +// @ts-expect-error Highcharts tooltip precision must retain its original type +const invalidTooltipPrecision: TooltipLine['chartKitPrecision'] = true; +`; + +const CONSUMER = CONSUMER_BASE + CONSUMER_CHECKS; + +const CONSUMER_MODES = [ + { + label: 'moduleResolution bundler', + type: 'module', + options: {module: 'esnext', moduleResolution: 'bundler'}, + source: CONSUMER, + }, + { + label: 'moduleResolution node', + type: 'commonjs', + options: {module: 'commonjs', moduleResolution: 'node', esModuleInterop: true}, + source: CONSUMER, + }, +]; + +function typecheckConsumers() { + const tsc = require.resolve('typescript/bin/tsc'); + const dir = mkdtempSync(join(tmpdir(), 'chartkit-consumer-')); + try { + // The package resolves through a symlink to the repository, and its dependencies from the + // repository's node_modules (TypeScript resolves the symlink to its real path). + mkdirSync(join(dir, 'node_modules', dirname(name)), {recursive: true}); + symlinkSync(ROOT, join(dir, 'node_modules', name), 'dir'); + for (const [index, mode] of CONSUMER_MODES.entries()) { + const project = join(dir, `mode-${index}`); + mkdirSync(project); + writeFileSync(join(project, 'package.json'), JSON.stringify({type: mode.type})); + writeFileSync(join(project, 'consumer.ts'), mode.source); + // skipLibCheck as in a typical application: the check is on what the consumer sees. + // No @types are picked up: the scratch project has none. + writeFileSync( + join(project, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + strict: true, + noEmit: true, + target: 'es2022', + skipLibCheck: true, + types: [], + ...mode.options, + }, + files: ['consumer.ts'], + }), + ); + const result = spawnSync(execPath, [tsc, '-p', project], { + cwd: project, + encoding: 'utf8', + }); + if (result.status === 0) { + stdout.write(`consumer (${mode.label}): types resolve\n`); + } else { + stderr.write( + `consumer (${mode.label}) fails to type-check:\n${result.stdout}${result.stderr}`, + ); + failed = true; + } + } + } finally { + rmSync(dir, {recursive: true, force: true}); + } +} + +typecheckConsumers(); + +if (failed) { + exit(1); +} +stdout.write('The built package preserves the indicator API in both resolution modes.\n'); diff --git a/src/components/ErrorBoundary/ErrorBoundary.tsx b/src/components/ErrorBoundary/ErrorBoundary.tsx index 2d45c1ab..2fca1981 100644 --- a/src/components/ErrorBoundary/ErrorBoundary.tsx +++ b/src/components/ErrorBoundary/ErrorBoundary.tsx @@ -2,13 +2,13 @@ import React from 'react'; import type {ChartKitError} from '../../libs'; import {CHARTKIT_ERROR_CODE} from '../../libs'; -import type {ChartKitOnError, ChartKitType, ChartKitWidget, RenderError} from '../../types'; +import type {ChartKitOnError, ChartKitProps, ChartKitType, RenderError} from '../../types'; import {getErrorMessage} from '../../utils/getErrorMessage'; type Props = { children: React.ReactNode; onError?: ChartKitOnError; - data: ChartKitWidget[ChartKitType]['data']; + data: ChartKitProps['data']; renderError?: RenderError; }; diff --git a/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-album-orientation-1-chromium-linux.png b/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-album-orientation-1-chromium-linux.png index 8e840b1f..348a9196 100644 Binary files a/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-album-orientation-1-chromium-linux.png and b/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-album-orientation-1-chromium-linux.png differ diff --git a/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-portrait-orientation-1-chromium-linux.png b/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-portrait-orientation-1-chromium-linux.png index 8085ee51..2406c06b 100644 Binary files a/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-portrait-orientation-1-chromium-linux.png and b/src/plugins/gravity-charts/__screenshots__/SplitTooltip.visual.test.tsx-screenshots/Split-tooltip-visual-tests-should-render-tooltip-in-portrait-orientation-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-default-state-1-chromium-linux.png b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-default-state-1-chromium-linux.png index 39336608..92446f48 100644 Binary files a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-default-state-1-chromium-linux.png and b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-default-state-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-independent-number-formats-1-chromium-linux.png b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-independent-number-formats-1-chromium-linux.png new file mode 100644 index 00000000..d9bc0257 Binary files /dev/null and b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-independent-number-formats-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-1-chromium-linux.png b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-1-chromium-linux.png new file mode 100644 index 00000000..8388d4cd Binary files /dev/null and b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-label-without-color-or-caption-1-chromium-linux.png b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-label-without-color-or-caption-1-chromium-linux.png new file mode 100644 index 00000000..9ea69b40 Binary files /dev/null and b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-label-without-color-or-caption-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-text-with-a-downward-arrow-1-chromium-linux.png b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-text-with-a-downward-arrow-1-chromium-linux.png new file mode 100644 index 00000000..989ad933 Binary files /dev/null and b/src/plugins/indicator/__screenshots__/Indicator.visual.test.tsx-screenshots/Indicator-visual-tests-secondary-value-below-text-with-a-downward-arrow-1-chromium-linux.png differ diff --git a/src/plugins/indicator/__stories__/Indicator.stories.tsx b/src/plugins/indicator/__stories__/Indicator.stories.tsx index 27002456..56633678 100644 --- a/src/plugins/indicator/__stories__/Indicator.stories.tsx +++ b/src/plugins/indicator/__stories__/Indicator.stories.tsx @@ -2,26 +2,13 @@ import React from 'react'; import {Button} from '@gravity-ui/uikit'; import {Meta, StoryObj} from '@storybook/react'; -import cloneDeep from 'lodash/cloneDeep'; import {action} from 'storybook/actions'; import {IndicatorPlugin} from '../'; import {ChartKit} from '../../../components/ChartKit'; import {settings} from '../../../libs'; -import type {ChartKitRef} from '../../../types'; -import type {IndicatorWidgetData, IndicatorWidgetDataItem} from '../types'; - -const data: IndicatorWidgetData = { - data: [ - { - content: { - current: { - value: 1539577973, - }, - }, - }, - ], -}; +import type {ChartKitProps, ChartKitRef} from '../../../types'; +import type {IndicatorWidgetDataItem} from '../public-types'; interface ChartStoryProps { color: string; @@ -33,14 +20,9 @@ interface ChartStoryProps { const ChartStory = ({color, size, title, nowrap}: ChartStoryProps) => { const [shown, setShown] = React.useState(false); const chartkitRef = React.useRef(undefined); - const resultData = cloneDeep(data); - - if (resultData.data) { - resultData.data[0].size = size; - resultData.data[0].color = color; - resultData.data[0].title = title; - resultData.data[0].nowrap = nowrap; - } + const resultData: ChartKitProps<'indicator'>['data'] = { + data: [{value: {value: 1539577973, color}, size, title, nowrap}], + }; if (!shown) { settings.set({plugins: [IndicatorPlugin]}); @@ -81,3 +63,59 @@ export const Showcase: StoryObj = { nowrap: {control: 'boolean'}, }, }; + +interface SecondaryValueStoryProps extends ChartStoryProps { + secondaryValuePosition: NonNullable['position']; + secondaryValue: Omit, 'position'>; +} + +export const WithSecondaryValue: StoryObj = { + 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)'],