From f29f96d65e9c22632b135e8724e45275e29bfe57 Mon Sep 17 00:00:00 2001 From: wangdicoder Date: Sat, 18 Apr 2026 22:02:09 +1000 Subject: [PATCH 1/2] feat(statistic): redesign metric api and docs --- .changeset/green-kids-cheer.md | 5 + .../__snapshots__/statistic.test.tsx.snap | 54 ++- .../statistic/__tests__/statistic.test.tsx | 120 ++--- packages/react/src/statistic/demo/Basic.tsx | 43 +- .../react/src/statistic/demo/Formatter.tsx | 32 +- packages/react/src/statistic/demo/States.tsx | 55 +++ packages/react/src/statistic/demo/Style.tsx | 50 +- packages/react/src/statistic/index.md | 250 +++++++++- packages/react/src/statistic/index.zh_CN.md | 250 +++++++++- packages/react/src/statistic/statistic.tsx | 434 +++++++++++++++--- packages/react/src/statistic/style/index.scss | 238 +++++++++- packages/react/src/statistic/types.ts | 78 +++- 12 files changed, 1372 insertions(+), 237 deletions(-) create mode 100644 .changeset/green-kids-cheer.md create mode 100644 packages/react/src/statistic/demo/States.tsx diff --git a/.changeset/green-kids-cheer.md b/.changeset/green-kids-cheer.md new file mode 100644 index 000000000..2e7b6a023 --- /dev/null +++ b/.changeset/green-kids-cheer.md @@ -0,0 +1,5 @@ +--- +'@tiny-design/react': major +--- + +Redesign the Statistic component with a product-grade metric API, richer states, improved docs guidance, and updated dashboard demos. diff --git a/packages/react/src/statistic/__tests__/__snapshots__/statistic.test.tsx.snap b/packages/react/src/statistic/__tests__/__snapshots__/statistic.test.tsx.snap index 4b5c2cc23..adff4b6e6 100644 --- a/packages/react/src/statistic/__tests__/__snapshots__/statistic.test.tsx.snap +++ b/packages/react/src/statistic/__tests__/__snapshots__/statistic.test.tsx.snap @@ -3,23 +3,67 @@ exports[` should match the snapshot 1`] = `
- Active Users +
+ Monthly Revenue +
+ Booked revenue across all active subscriptions. +
+
- 112,893 + $128,430.50
+
+
+
+
+
+
`; diff --git a/packages/react/src/statistic/__tests__/statistic.test.tsx b/packages/react/src/statistic/__tests__/statistic.test.tsx index 54695f1e9..16ff668b0 100644 --- a/packages/react/src/statistic/__tests__/statistic.test.tsx +++ b/packages/react/src/statistic/__tests__/statistic.test.tsx @@ -4,84 +4,94 @@ import Statistic from '../index'; describe('', () => { it('should match the snapshot', () => { - const { asFragment } = render(); + const { asFragment } = render( + + ); expect(asFragment()).toMatchSnapshot(); }); - it('should render correctly', () => { - const { container } = render(); - expect(container.firstChild).toHaveClass('ty-statistic'); - }); - - it('should render title', () => { - const { getByText } = render(); - expect(getByText('Total Sales')).toBeInTheDocument(); - }); - - it('should format value with group separator', () => { - const { getByText } = render(); - expect(getByText('112,893')).toBeInTheDocument(); - }); - - it('should format value with precision', () => { - const { getByText } = render(); - expect(getByText('11.28')).toBeInTheDocument(); - }); - - it('should support custom decimal separator', () => { + it('should render currency formatting', () => { const { getByText } = render( - + ); - expect(getByText('112.893,5')).toBeInTheDocument(); + expect(getByText('$128,430.50')).toBeInTheDocument(); }); - it('should render prefix and suffix', () => { + it('should render percent formatting', () => { const { getByText } = render( - + ); - expect(getByText('$')).toBeInTheDocument(); - expect(getByText('USD')).toBeInTheDocument(); - }); - - it('should use custom formatter', () => { - const formatter = (val: number | string) => `${val}%`; - const { getByText } = render(); - expect(getByText('95%')).toBeInTheDocument(); + expect(getByText('23.86%')).toBeInTheDocument(); }); - it('should pass formatting info to formatter', () => { - const formatter = jest.fn((_: number | string, info) => info.formattedValue); - const { getByText } = render(); - expect(getByText('2,386.4')).toBeInTheDocument(); + it('should support custom formatter', () => { + const formatter = jest.fn((_, info) => `${info.formattedValue} live`); + const { getByText } = render( + + ); + expect(getByText('112.9K live')).toBeInTheDocument(); expect(formatter).toHaveBeenCalledWith( - 2386.4, + 112893, expect.objectContaining({ - formattedValue: '2,386.4', - groupSeparator: ',', - decimalSeparator: '.', - precision: 1, + formattedValue: '112.9K', isNumeric: true, }) ); }); - it('should render string value', () => { - const { getByText } = render(); - expect(getByText('N/A')).toBeInTheDocument(); + it('should render loading skeleton', () => { + const { container } = render(); + expect(container.querySelector('.ty-skeleton')).toBeInTheDocument(); + }); + + it('should render empty placeholder for null value', () => { + const { getByText } = render(); + expect(getByText('No data')).toBeInTheDocument(); }); - it('should render empty placeholder for invalid number', () => { - const { getByText } = render(); - expect(getByText('--')).toBeInTheDocument(); + it('should render error state before value', () => { + const { getByText, queryByText } = render( + + ); + expect(getByText('Feed unavailable')).toBeInTheDocument(); + expect(queryByText('95')).not.toBeInTheDocument(); }); - it('should support custom empty placeholder', () => { - const { getByText } = render(); - expect(getByText('Pending')).toBeInTheDocument(); + it('should render trend and status', () => { + const { container, getByText } = render( + + ); + expect(getByText('-2%')).toBeInTheDocument(); + expect(getByText('Below target')).toBeInTheDocument(); + expect(container.querySelector('.ty-statistic__trend_negative')).toBeInTheDocument(); + expect(container.querySelector('.ty-statistic__status_warning')).toBeInTheDocument(); }); - it('should apply value class name', () => { - const { container } = render(); - expect(container.querySelector('.ty-statistic__content')).toHaveClass('custom-value'); + it('should build aria label from the rendered metric content', () => { + const { container } = render( + + ); + + expect(container.querySelector('.ty-statistic__content')).toHaveAttribute( + 'aria-label', + 'Revenue, $128,430.50, up +12.4% vs last month, success Healthy growth' + ); }); }); diff --git a/packages/react/src/statistic/demo/Basic.tsx b/packages/react/src/statistic/demo/Basic.tsx index 9ea58778b..edf6bb1cd 100644 --- a/packages/react/src/statistic/demo/Basic.tsx +++ b/packages/react/src/statistic/demo/Basic.tsx @@ -1,12 +1,45 @@ import React from 'react'; -import { Statistic, Flex } from '@tiny-design/react'; +import { Card, Flex, Statistic } from '@tiny-design/react'; export default function BasicDemo() { return ( - - - - + + + + + + + + + + + + + + + + ); } diff --git a/packages/react/src/statistic/demo/Formatter.tsx b/packages/react/src/statistic/demo/Formatter.tsx index 2ce14efd7..70712a03c 100644 --- a/packages/react/src/statistic/demo/Formatter.tsx +++ b/packages/react/src/statistic/demo/Formatter.tsx @@ -1,22 +1,30 @@ import React from 'react'; -import { Statistic, Flex } from '@tiny-design/react'; +import { Flex, Statistic } from '@tiny-design/react'; export default function FormatterDemo() { return ( - + { - const diff = Math.max(0, Math.floor((Number(val) - Date.now()) / 3600000)); - return `${diff}h remaining`; - }} + title="Compact Number" + value={3498200} + format={{ type: 'compact', maximumFractionDigits: 1 }} + size="sm" /> {info.formattedValue}%} + title="German Revenue" + value={1128930.5} + format={{ type: 'currency', currency: 'EUR', locale: 'de-DE', maximumFractionDigits: 2 }} + /> + + ); diff --git a/packages/react/src/statistic/demo/States.tsx b/packages/react/src/statistic/demo/States.tsx new file mode 100644 index 000000000..eefa29f8e --- /dev/null +++ b/packages/react/src/statistic/demo/States.tsx @@ -0,0 +1,55 @@ +import React from 'react'; +import { Card, Flex, Statistic } from '@tiny-design/react'; + +export default function StatesDemo() { + return ( + + + + + + + + + + + + + + + + + + + + + + + ); +} diff --git a/packages/react/src/statistic/demo/Style.tsx b/packages/react/src/statistic/demo/Style.tsx index e82ba480f..74847cb46 100644 --- a/packages/react/src/statistic/demo/Style.tsx +++ b/packages/react/src/statistic/demo/Style.tsx @@ -1,29 +1,35 @@ import React from 'react'; -import { Statistic, Flex } from '@tiny-design/react'; +import { Card, Flex, Statistic } from '@tiny-design/react'; export default function StyleDemo() { return ( - - - - + + + + + + + + + + + ); } diff --git a/packages/react/src/statistic/index.md b/packages/react/src/statistic/index.md index 97e36750f..deb40e2ba 100644 --- a/packages/react/src/statistic/index.md +++ b/packages/react/src/statistic/index.md @@ -4,14 +4,16 @@ import FormatterDemo from './demo/Formatter'; import FormatterSource from './demo/Formatter.tsx?raw'; import StyleDemo from './demo/Style'; import StyleSource from './demo/Style.tsx?raw'; +import StatesDemo from './demo/States'; +import StatesSource from './demo/States.tsx?raw'; # Statistic -Display key figures with clear formatting, prefix/suffix content, and customizable rendering. +Product-grade metric display with internationalized formatting, semantic states, trend indicators, and supporting context. ## Scenario -Used in dashboards and data-heavy pages to highlight key performance indicators (KPIs), financial numbers, and progress metrics. +Use `Statistic` in dashboards, metric cards, review pages, and operational surfaces where a number needs structure around it: title, description, trend, health state, loading, and supporting copy. ## Usage @@ -25,18 +27,18 @@ import { Statistic } from 'tiny-design'; -### Basic +### Dashboard Metrics -Display a statistic with title, numeric formatting, and prefix/suffix content. +Show the metric itself together with context, trend, and health. -### Custom Formatter +### Formatting -Use `formatter` to customize rendering while still receiving the formatted value. +Use `format` to switch between currency, percent, compact, and duration displays. @@ -45,30 +47,232 @@ Use `formatter` to customize rendering while still receiving the formatted value -### Value Style +### Product Composition -Customize separators, empty state, and value appearance. +Compose `Statistic` inside cards with tooltip, footer, and operational context. + + + +### States + +Compare loading, empty, error, and resolved value states with a consistent card layout. + + + ## Props -| Property | Description | Type | Default | -| -------------- | ------------------------------------------------ | ----------------------------------------- | ------- | -| title | title of the statistic | ReactNode | | -| value | the value to display | number \| string | | -| precision | number of decimal places | number | | -| prefix | prefix node of value | ReactNode | | -| suffix | suffix node of value | ReactNode | | -| groupSeparator | thousands separator | string | , | -| decimalSeparator | decimal separator | string | . | -| valueStyle | custom style for value | CSSProperties | | -| valueClassName | custom class name for value container | string | | -| empty | placeholder content for empty or invalid values | ReactNode | -- | -| formatter | custom value formatter | (value: number \| string, info: StatisticFormatterInfo) => ReactNode | | - -`formatter` receives a second argument with `formattedValue`, `groupSeparator`, `decimalSeparator`, `precision`, and `isNumeric`, so custom rendering can reuse the component's built-in formatting rules. +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| title | Metric title | `ReactNode` | - | +| description | Supporting copy shown under the title | `ReactNode` | - | +| tooltip | Tooltip content shown beside the title | `ReactNode` | - | +| value | Metric value | `number \| string \| null` | - | +| format | Declarative formatting options for numeric values | `StatisticFormatOptions` | `{ type: 'number' }` | +| prefix | Content before the value | `ReactNode` | - | +| suffix | Content after the value | `ReactNode` | - | +| formatter | Full custom renderer for the value area | `(value, info) => ReactNode` | - | +| trend | Trend indicator with direction, value, label, and sentiment | `StatisticTrend` | - | +| status | Semantic health state | `StatisticStatus` | - | +| extra | Auxiliary content shown next to trend/status | `ReactNode` | - | +| footer | Footer content below the metric | `ReactNode` | - | +| loading | Whether to show the loading skeleton | `boolean` | `false` | +| skeleton | Custom loading placeholder | `ReactNode` | - | +| empty | Empty-state content when value is missing or invalid | `ReactNode` | `--` | +| error | Error-state content. When provided it overrides value rendering | `ReactNode` | - | +| size | Metric scale | `'sm' \| 'md' \| 'lg'` | `'md'` | +| emphasis | Value font emphasis | `'normal' \| 'strong'` | `'strong'` | +| align | Horizontal alignment | `'start' \| 'center' \| 'end'` | `'start'` | +| monospace | Apply tabular numbers to the value | `boolean` | `true` | +| valueClassName | Custom class for the value container | `string` | - | +| titleClassName | Custom class for the title | `string` | - | +| trendClassName | Custom class for the trend container | `string` | - | +| valueStyle | Inline style for the value container | `CSSProperties` | - | +| titleStyle | Inline style for the title | `CSSProperties` | - | +| trendStyle | Inline style for the trend container | `CSSProperties` | - | + +## StatisticFormatOptions + +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| type | Format mode | `'number' \| 'decimal' \| 'percent' \| 'currency' \| 'compact' \| 'duration' \| 'custom'` | `'number'` | +| locale | BCP 47 locale for `Intl.NumberFormat` | `string` | `'en-US'` | +| currency | Currency code used when `type='currency'` | `string` | - | +| minimumFractionDigits | Minimum fraction digits | `number` | - | +| maximumFractionDigits | Maximum fraction digits | `number` | - | +| useGrouping | Whether to group thousands | `boolean` | - | +| notation | Number notation | `'standard' \| 'compact'` | - | +| compactDisplay | Compact display style | `'short' \| 'long'` | `'short'` | +| unit | `Intl` unit name for decimal values | `Intl.NumberFormatOptions['unit']` | - | +| unitDisplay | Unit display style | `'short' \| 'long' \| 'narrow'` | - | +| signDisplay | Sign display mode | `'auto' \| 'always' \| 'never' \| 'exceptZero'` | - | +| durationUnit | Input unit when `type='duration'` | `'ms' \| 's'` | `'ms'` | + +## StatisticTrend + +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| direction | Visual direction of the trend indicator | `'up' \| 'down' \| 'flat'` | - | +| value | Main trend content, usually a delta such as `+12.4%` | `ReactNode` | - | +| label | Secondary context for the trend, such as `vs last month` | `ReactNode` | - | +| sentiment | Semantic meaning of the trend color. Keep this separate from direction because a downward trend can be good in some products | `'positive' \| 'negative' \| 'neutral'` | - | +| icon | Custom icon used instead of the built-in arrow/flat marker | `ReactNode` | - | + +Example: + +```tsx +trend={{ + direction: 'up', + value: '+12.4%', + label: 'vs last month', + sentiment: 'positive', +}} +``` + +## StatisticStatus + +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| type | Semantic state used for status color | `'default' \| 'success' \| 'warning' \| 'danger' \| 'info'` | `'default'` | +| text | Status copy shown next to the status dot | `ReactNode` | - | + +Example: + +```tsx +status={{ + type: 'warning', + text: 'Above weekly target', +}} +``` + +## StatisticRenderInfo + +This object is passed as the second argument to `formatter`. + +| Property | Description | Type | +| --- | --- | --- | +| rawValue | Original `value` passed into the component | `number \| string \| null \| undefined` | +| formattedValue | Value formatted by the built-in formatter | `string` | +| locale | Resolved locale used during formatting | `string` | +| isEmpty | Whether the value is considered empty and would fall back to `empty` | `boolean` | +| isNumeric | Whether the original value is a finite number | `boolean` | +| parts | Optional `Intl.NumberFormat#formatToParts` result for advanced rendering | `Intl.NumberFormatPart[] \| undefined` | + +Example: + +```tsx + ( + + {info.formattedValue} + {info.isNumeric ? ' ARR' : ''} + + )} +/> +``` + +## Rendering Priority + +`Statistic` resolves display states in the following order: + +1. `loading` +2. `error` +3. `empty` +4. `value` + +That means: + +- When `loading` is `true`, the component shows the skeleton placeholder and does not render the value. +- When `error` is provided, it overrides normal value rendering. +- When `value` is empty or invalid (`null`, `undefined`, `''`, `NaN`, `Infinity`), the component falls back to `empty`. +- Only when none of the above apply does the component render the formatted value or `formatter` result. + +## Design Guidance + +- Use `title` for the metric label only. Keep it short and scannable. +- Use `description` for contextual explanation, source, or time window. It should read as supporting copy, not as a second title. +- Use `trend` for directional change such as growth, decline, or stability. Keep it compact. +- Use `status` for semantic health or operational state such as `Healthy`, `Delayed`, or `Data unavailable`. +- Keep `direction` and `sentiment` separate. For example, a complaint rate going down is usually `direction: 'down'` and `sentiment: 'positive'`. +- Prefer short primary error states such as `Unavailable` or `Sync failed`, and move details into `status`, `description`, or `footer`. +- Keep empty states concise. They should not visually overpower a valid metric value. +- Use `formatter` for advanced display logic, but prefer `format` whenever standard number, percent, currency, compact, or duration formatting is sufficient. + +## Common Patterns + +### KPI Card + +Use when a dashboard needs to highlight a core business number with a short trend summary. + +```tsx + +``` + +### Operational Status + +Use when the primary message is whether a system or feed is healthy, delayed, or unavailable. + +```tsx + +``` + +### Financial Metric + +Use when currency, locale, and semantic health all matter. + +```tsx + +``` + +### SLA or Performance Metric + +Use when the metric is duration-based and should be paired with a compact operational status. + +```tsx + +``` diff --git a/packages/react/src/statistic/index.zh_CN.md b/packages/react/src/statistic/index.zh_CN.md index 847dad114..6284ce18b 100644 --- a/packages/react/src/statistic/index.zh_CN.md +++ b/packages/react/src/statistic/index.zh_CN.md @@ -4,14 +4,16 @@ import FormatterDemo from './demo/Formatter'; import FormatterSource from './demo/Formatter.tsx?raw'; import StyleDemo from './demo/Style'; import StyleSource from './demo/Style.tsx?raw'; +import StatesDemo from './demo/States'; +import StatesSource from './demo/States.tsx?raw'; # Statistic 统计数值 -展示关键统计数值,支持数值格式化、前后缀和自定义渲染。 +面向产品场景的指标展示组件,支持国际化格式化、状态表达、趋势信息和辅助上下文。 ## 使用场景 -用于仪表盘和数据密集页面,突出展示 KPI、财务数字和进度指标。 +适用于仪表盘、经营分析、指标卡片、运维面板等场景。除了显示数值本身,还可以统一承载标题、说明、趋势、健康状态、加载态和补充信息。 ## 使用方式 @@ -25,18 +27,18 @@ import { Statistic } from 'tiny-design'; -### 基本用法 +### 仪表盘指标 -展示带标题、数值格式化和前后缀的统计组件。 +同时展示指标数值、背景说明、趋势和健康状态。 -### 自定义格式化 +### 数值格式化 -使用 `formatter` 自定义数值显示,同时复用内置格式化结果。 +通过 `format` 在货币、百分比、紧凑数值和时长等模式之间切换。 @@ -45,30 +47,232 @@ import { Statistic } from 'tiny-design'; -### 数值样式 +### 产品化组合 -通过分隔符、空态占位和样式来自定义数值外观。 +在卡片中组合 `Statistic`,展示 Tooltip、页脚说明和业务上下文。 + + + +### 状态表达 + +用统一的卡片结构对比 loading、empty、error 和正常值状态。 + + + ## Props -| 属性 | 说明 | 类型 | 默认值 | -| -------------- | ------------------------ | ----------------------------------------- | ------- | -| title | 统计标题 | ReactNode | | -| value | 展示的数值 | number \| string | | -| precision | 小数点精度 | number | | -| prefix | 数值前缀 | ReactNode | | -| suffix | 数值后缀 | ReactNode | | -| groupSeparator | 千分位分隔符 | string | , | -| decimalSeparator | 小数分隔符 | string | . | -| valueStyle | 数值样式 | CSSProperties | | -| valueClassName | 数值容器自定义类名 | string | | -| empty | 空值或非法数值占位内容 | ReactNode | -- | -| formatter | 自定义格式化函数 | (value: number \| string, info: StatisticFormatterInfo) => ReactNode | | - -`formatter` 的第二个参数会提供 `formattedValue`、`groupSeparator`、`decimalSeparator`、`precision` 和 `isNumeric`,方便在自定义渲染时复用组件内置格式化逻辑。 +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| title | 指标标题 | `ReactNode` | - | +| description | 标题下方的辅助说明 | `ReactNode` | - | +| tooltip | 标题旁的提示内容 | `ReactNode` | - | +| value | 指标值 | `number \| string \| null` | - | +| format | 数值格式化配置 | `StatisticFormatOptions` | `{ type: 'number' }` | +| prefix | 数值前缀内容 | `ReactNode` | - | +| suffix | 数值后缀内容 | `ReactNode` | - | +| formatter | 完全自定义数值渲染 | `(value, info) => ReactNode` | - | +| trend | 趋势信息,包含方向、数值、标签和语义倾向 | `StatisticTrend` | - | +| status | 指标健康状态 | `StatisticStatus` | - | +| extra | 趋势/状态旁边的辅助信息 | `ReactNode` | - | +| footer | 数值下方页脚内容 | `ReactNode` | - | +| loading | 是否显示骨架屏 | `boolean` | `false` | +| skeleton | 自定义加载占位 | `ReactNode` | - | +| empty | 空值或非法值时的占位内容 | `ReactNode` | `--` | +| error | 错误态内容,存在时优先于数值显示 | `ReactNode` | - | +| size | 尺寸 | `'sm' \| 'md' \| 'lg'` | `'md'` | +| emphasis | 主数值字重层级 | `'normal' \| 'strong'` | `'strong'` | +| align | 水平对齐方式 | `'start' \| 'center' \| 'end'` | `'start'` | +| monospace | 是否对主数值启用等宽数字 | `boolean` | `true` | +| valueClassName | 数值区域自定义类名 | `string` | - | +| titleClassName | 标题自定义类名 | `string` | - | +| trendClassName | 趋势区域自定义类名 | `string` | - | +| valueStyle | 数值区域样式 | `CSSProperties` | - | +| titleStyle | 标题样式 | `CSSProperties` | - | +| trendStyle | 趋势区域样式 | `CSSProperties` | - | + +## StatisticFormatOptions + +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| type | 格式化模式 | `'number' \| 'decimal' \| 'percent' \| 'currency' \| 'compact' \| 'duration' \| 'custom'` | `'number'` | +| locale | `Intl.NumberFormat` 使用的 locale | `string` | `'en-US'` | +| currency | `type='currency'` 时的货币代码 | `string` | - | +| minimumFractionDigits | 最小小数位数 | `number` | - | +| maximumFractionDigits | 最大小数位数 | `number` | - | +| useGrouping | 是否启用千分位分组 | `boolean` | - | +| notation | 数字记数法 | `'standard' \| 'compact'` | - | +| compactDisplay | 紧凑格式展示方式 | `'short' \| 'long'` | `'short'` | +| unit | 十进制数值的 `Intl` 单位名 | `Intl.NumberFormatOptions['unit']` | - | +| unitDisplay | 单位显示方式 | `'short' \| 'long' \| 'narrow'` | - | +| signDisplay | 正负号展示策略 | `'auto' \| 'always' \| 'never' \| 'exceptZero'` | - | +| durationUnit | `type='duration'` 时输入值的单位 | `'ms' \| 's'` | `'ms'` | + +## StatisticTrend + +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| direction | 趋势图标方向 | `'up' \| 'down' \| 'flat'` | - | +| value | 趋势主内容,通常是 `+12.4%` 这样的变化值 | `ReactNode` | - | +| label | 趋势辅助说明,例如 `vs last month` | `ReactNode` | - | +| sentiment | 趋势语义颜色。它应与 direction 解耦,因为有些业务里下降反而是正向结果 | `'positive' \| 'negative' \| 'neutral'` | - | +| icon | 自定义趋势图标,会替代内置箭头/横线图标 | `ReactNode` | - | + +示例: + +```tsx +trend={{ + direction: 'up', + value: '+12.4%', + label: 'vs last month', + sentiment: 'positive', +}} +``` + +## StatisticStatus + +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| type | 状态语义颜色 | `'default' \| 'success' \| 'warning' \| 'danger' \| 'info'` | `'default'` | +| text | 状态圆点旁边的说明文案 | `ReactNode` | - | + +示例: + +```tsx +status={{ + type: 'warning', + text: 'Above weekly target', +}} +``` + +## StatisticRenderInfo + +该对象会作为 `formatter` 的第二个参数传入。 + +| 属性 | 说明 | 类型 | +| --- | --- | --- | +| rawValue | 传入组件的原始 `value` | `number \| string \| null \| undefined` | +| formattedValue | 经过内置格式化后的值 | `string` | +| locale | 实际用于格式化的 locale | `string` | +| isEmpty | 当前值是否会被判定为空并回退到 `empty` | `boolean` | +| isNumeric | 原始值是否为有限数字 | `boolean` | +| parts | 可选的 `Intl.NumberFormat#formatToParts` 结果,适合做高级自定义渲染 | `Intl.NumberFormatPart[] \| undefined` | + +示例: + +```tsx + ( + + {info.formattedValue} + {info.isNumeric ? ' ARR' : ''} + + )} +/> +``` + +## 渲染优先级 + +`Statistic` 会按以下顺序决定当前显示状态: + +1. `loading` +2. `error` +3. `empty` +4. `value` + +也就是说: + +- 当 `loading` 为 `true` 时,组件显示骨架屏,不渲染数值。 +- 当传入 `error` 时,错误态会覆盖正常数值显示。 +- 当 `value` 为空或非法(`null`、`undefined`、`''`、`NaN`、`Infinity`)时,组件会回退到 `empty`。 +- 只有以上情况都不满足时,组件才会渲染格式化后的数值或 `formatter` 的结果。 + +## 设计建议 + +- `title` 只用于指标名称,尽量短、易扫读。 +- `description` 用于补充上下文、口径来源或时间范围,它应当是辅助说明,而不是第二个标题。 +- `trend` 适合表达涨跌、变化和稳定趋势,内容应尽量紧凑。 +- `status` 适合表达健康状态或运营状态,例如 `Healthy`、`Delayed`、`Data unavailable`。 +- `direction` 和 `sentiment` 应当解耦。例如投诉率下降通常应写成 `direction: 'down'`,但 `sentiment: 'positive'`。 +- 错误态主文案建议简短,如 `Unavailable`、`Sync failed`,详细原因可以放在 `status`、`description` 或 `footer`。 +- 空态文案应当克制,不要在视觉上压过正常指标值。 +- 需要复杂展示时使用 `formatter`,但如果只是标准数值、百分比、货币、紧凑数值或时长格式,优先使用 `format`。 + +## 常见模式 + +### KPI 卡片 + +适用于仪表盘中需要突出展示核心业务指标,并附带简短趋势信息的场景。 + +```tsx + +``` + +### 运营状态指标 + +适用于核心信息是系统、数据流或任务是否健康、延迟或不可用的场景。 + +```tsx + +``` + +### 财务指标 + +适用于需要同时关注货币/百分比格式、趋势变化和健康状态的财务场景。 + +```tsx + +``` + +### SLA / 性能指标 + +适用于时长类指标,并且需要搭配简洁运营状态说明的场景。 + +```tsx + +``` diff --git a/packages/react/src/statistic/statistic.tsx b/packages/react/src/statistic/statistic.tsx index 303a25698..aa7d51353 100644 --- a/packages/react/src/statistic/statistic.tsx +++ b/packages/react/src/statistic/statistic.tsx @@ -2,54 +2,103 @@ import React, { useContext } from 'react'; import classNames from 'classnames'; import { ConfigContext } from '../config-provider/config-context'; import { getPrefixCls } from '../_utils/general'; -import { StatisticFormatterInfo, StatisticProps } from './types'; +import Skeleton from '../skeleton'; +import Tooltip from '../tooltip'; +import { + StatisticAlign, + StatisticEmphasis, + StatisticFormatOptions, + StatisticProps, + StatisticRenderInfo, + StatisticStatus, + StatisticTrend, + StatisticValue, +} from './types'; -const getSafePrecision = (precision?: number): number | undefined => { - if (typeof precision !== 'number' || Number.isNaN(precision) || precision < 0) { +const DEFAULT_LOCALE = 'en-US'; + +const clampFractionDigits = (value?: number): number | undefined => { + if (typeof value !== 'number' || Number.isNaN(value) || value < 0) { return undefined; } - return Math.floor(precision); + return Math.floor(value); +}; + +const getIntlOptions = (format: StatisticFormatOptions = {}): Intl.NumberFormatOptions => { + const { + type = 'number', + currency, + minimumFractionDigits, + maximumFractionDigits, + useGrouping, + notation, + compactDisplay, + unit, + unitDisplay, + signDisplay, + } = format; + + const options: Intl.NumberFormatOptions = { + minimumFractionDigits: clampFractionDigits(minimumFractionDigits), + maximumFractionDigits: clampFractionDigits(maximumFractionDigits), + useGrouping, + signDisplay, + }; + + if (type === 'percent') { + options.style = 'percent'; + } else if (type === 'currency' && currency) { + options.style = 'currency'; + options.currency = currency; + } else if (unit) { + options.style = 'unit'; + options.unit = unit; + options.unitDisplay = unitDisplay; + } else { + options.style = 'decimal'; + } + + if (type === 'compact' || notation === 'compact') { + options.notation = 'compact'; + options.compactDisplay = compactDisplay ?? 'short'; + } else if (notation) { + options.notation = notation; + } + + return options; }; -const formatNumericValue = ( - value: number, - precision?: number, - groupSeparator = ',', - decimalSeparator = '.' -): string => { - const normalizedPrecision = getSafePrecision(precision); - const sign = value < 0 ? '-' : ''; - const raw = normalizedPrecision !== undefined - ? Math.abs(value).toFixed(normalizedPrecision) - : String(Math.abs(value)); - const [integerPart, decimalPart] = raw.split('.'); - const groupedInteger = groupSeparator - ? integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator) - : integerPart; - - if (!decimalPart) { - return `${sign}${groupedInteger}`; +const formatDuration = (value: number, unit: StatisticFormatOptions['durationUnit'] = 'ms'): string => { + const totalSeconds = Math.max(0, Math.floor(unit === 's' ? value : value / 1000)); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + const parts: string[] = []; + + if (hours > 0) { + parts.push(`${hours}h`); } - return `${sign}${groupedInteger}${decimalSeparator}${decimalPart}`; + if (minutes > 0 || hours > 0) { + parts.push(`${minutes}m`); + } + + parts.push(`${seconds}s`); + + return parts.join(' '); }; -const getDisplayInfo = ( - value: number | string | undefined, - precision?: number, - groupSeparator = ',', - decimalSeparator = '.' -): StatisticFormatterInfo & { rawValue: number | string; hasValue: boolean } => { - if (value === undefined) { +const formatValue = (value: StatisticValue, format: StatisticFormatOptions = {}): StatisticRenderInfo => { + const locale = format.locale || DEFAULT_LOCALE; + + if (value === null || value === undefined || value === '') { return { - rawValue: '', + rawValue: value, formattedValue: '', - groupSeparator, - decimalSeparator, - precision: getSafePrecision(precision), + locale, + isEmpty: true, isNumeric: false, - hasValue: false, }; } @@ -57,11 +106,9 @@ const getDisplayInfo = ( return { rawValue: value, formattedValue: value, - groupSeparator, - decimalSeparator, - precision: getSafePrecision(precision), + locale, + isEmpty: false, isNumeric: false, - hasValue: value.length > 0, }; } @@ -69,73 +116,322 @@ const getDisplayInfo = ( return { rawValue: value, formattedValue: '', - groupSeparator, - decimalSeparator, - precision: getSafePrecision(precision), + locale, + isEmpty: true, + isNumeric: true, + }; + } + + if (format.type === 'duration') { + return { + rawValue: value, + formattedValue: formatDuration(value, format.durationUnit), + locale, + isEmpty: false, isNumeric: true, - hasValue: false, }; } + const numberFormat = new Intl.NumberFormat(locale, getIntlOptions(format)); + return { rawValue: value, - formattedValue: formatNumericValue(value, precision, groupSeparator, decimalSeparator), - groupSeparator, - decimalSeparator, - precision: getSafePrecision(precision), + formattedValue: numberFormat.format(value), + locale, + isEmpty: false, isNumeric: true, - hasValue: true, + parts: numberFormat.formatToParts(value), }; }; +const getTextLabel = (content: React.ReactNode): string => { + if (typeof content === 'string' || typeof content === 'number') { + return String(content); + } + + return ''; +}; + +const getTrendText = (trend?: StatisticTrend): string => { + if (!trend) { + return ''; + } + + const directionMap: Record, string> = { + up: 'up', + down: 'down', + flat: 'flat', + }; + const parts = [ + trend.direction ? directionMap[trend.direction] : '', + getTextLabel(trend.value), + getTextLabel(trend.label), + ].filter(Boolean); + + return parts.join(' '); +}; + +const getStatusText = (status?: StatisticStatus): string => { + if (!status) { + return ''; + } + + return [status.type && status.type !== 'default' ? status.type : '', getTextLabel(status.text)] + .filter(Boolean) + .join(' '); +}; + +const getAriaLabel = ( + label: string | undefined, + title: React.ReactNode, + prefix: React.ReactNode, + suffix: React.ReactNode, + displayValue: React.ReactNode, + formattedValue: string, + trend?: StatisticTrend, + status?: StatisticStatus +): string | undefined => { + if (label) { + return label; + } + + const parts = [ + getTextLabel(title), + getTextLabel(prefix), + getTextLabel(displayValue) || formattedValue, + getTextLabel(suffix), + getTrendText(trend), + getStatusText(status), + ].filter(Boolean); + + return parts.length > 0 ? parts.join(', ') : undefined; +}; + +const getTrendIcon = (prefixCls: string, trend: StatisticTrend): React.ReactNode => { + if (trend.icon) { + return trend.icon; + } + + if (!trend.direction) { + return null; + } + + return ( +