# Chart

Ten typed chart forms with ordered palette roles, responsive geometry, shared inspection and an accessible data table. Compose with Card and DataTrend for metric panels.

## Cách dùng

### Khi nào dùng

- Show changes, comparisons, composition, conversion, retention or service availability from numeric data.
- Keep an accessible data table beside visual patterns and point inspection.

### Khi nào không dùng

- A single current value and its change. Use DataTrend.
- Completion toward a known total. Use Progress.
- Editing individual measurements. Use Table with form controls.

## Biến thể

### type

Required discriminant. Each type accepts only its own data shape.

Giá trị: `line`, `area`, `bar`, `sparkline`, `composition`, `donut`, `funnel`, `timeline`, `cohort`, `uptime`. Mặc định: `undefined`.

### table

Toggle reveals the semantic data view. Hidden keeps the table accessible with visually hidden presentation. Sparkline defaults hidden.

Giá trị: `toggle`, `visible`, `hidden`. Mặc định: `toggle`.

### xScale

Cartesian axis spacing. Numeric and time modes require finite, strictly ascending x values; time uses epoch milliseconds. Without formatX, time positions show a short UTC date.

Giá trị: `category`, `linear`, `time`. Mặc định: `category`.

### stack

Area only: overlaid independent series or a nonnegative summed stack. Null breaks the stack at that row.

Giá trị: `none`, `normal`. Mặc định: `none`.

### orientation

Bar only: vertical or horizontal bars.

Giá trị: `vertical`, `horizontal`. Mặc định: `vertical`.

### layout

Bar only: grouped, signed stacked or nonnegative percentage composition. Percentage rows with zero totals stay empty.

Giá trị: `grouped`, `stacked`, `percentage`. Mặc định: `grouped`.

## Ví dụ

### Three-series line

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="line" label="Weekly activity" data={sampleChartRows} series={sampleChartSeries} />
```

### Overlaid areas

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="area" label="Audience over time" data={sampleChartRows} series={sampleChartSeries} stack="none" />
```

### Stacked areas

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="area" label="Allocation over time" data={sampleChartRows} series={sampleChartSeries} stack="normal" />
```

### Vertical grouped bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Grouped activity" data={sampleChartRows} series={sampleChartSeries} orientation="vertical" layout="grouped" />
```

### Vertical stacked bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Stacked activity" data={sampleChartRows} series={sampleChartSeries} orientation="vertical" layout="stacked" />
```

### Vertical percentage bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Percentage activity" data={sampleChartRows} series={sampleChartSeries} orientation="vertical" layout="percentage" />
```

### Horizontal grouped bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Grouped activity" data={sampleChartRows} series={sampleChartSeries} orientation="horizontal" layout="grouped" />
```

### Horizontal stacked bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Stacked activity" data={sampleChartRows} series={sampleChartSeries} orientation="horizontal" layout="stacked" />
```

### Horizontal percentage bars

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Percentage activity" data={sampleChartRows} series={sampleChartSeries} orientation="horizontal" layout="percentage" />
```

### Compact table bar

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Views against a shared maximum" data={sampleChartRows} series={sampleSparkSeries} orientation="horizontal" compact domain={[0, 600]} table="hidden" />
```

### Sparkline

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="sparkline" label="Views this week" data={sampleChartRows} series={sampleSparkSeries} />
```

### Composition

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="composition" label="Traffic sources" data={sampleChartParts} />
```

### Donut

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="donut" label="Traffic sources" data={sampleChartParts} />
```

### Ordered funnel

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="funnel" label="Journey conversion" data={sampleFunnelParts} />
```

### Timeline

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="timeline" label="Delivery schedule" data={sampleChartRanges} range={[0, 28]} marker={{ value: 14, label: "Checkpoint" }} />
```

### Cohort retention

Original illustrative cohorts. Null means not yet observed; zero means an observed zero percent.

```tsx
<Chart type="cohort" label="Weekly retention" data={sampleChartCohorts} columns={sampleCohortColumns} />
```

### Service uptime

Original equal-duration observations. Unknown periods remain explicit; summaries average known availability.

```tsx
<Chart type="uptime" label="Daily service availability" data={sampleChartUptime} />
```

### Current and prior periods

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="line" label="Current and prior activity" data={sampleComparisonRows} series={sampleComparisonSeries} />
```

### Missing values

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="line" label="Activity with an observation gap" data={sampleMissingRows} series={sampleChartSeries} />
```

### Signed values

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="bar" label="Regional net changes" data={sampleSignedRows} series={sampleSignedSeries} layout="stacked" />
```

### Empty total

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="donut" label="Activity awaiting observations" data={sampleZeroParts} />
```

### Eight series

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="line" label="Eight labeled groups" data={sampleEightRows} series={sampleEightSeries} />
```

### Pending refresh

Original illustrative data stays visible while only the plot dims.

```tsx
<Chart type="line" label="Activity being refreshed" data={sampleChartRows} series={sampleChartSeries} pending />
```

### Localized labels

Original illustrative data. Copy includes the complete local setup.

```tsx
<Chart type="line" label="Activity with custom labels" data={sampleMissingRows} series={sampleChartSeries} locale="en-GB" labels={sampleChartLabels} />
```

## Nên và không nên

### Nên

- Use the ten discriminated data contracts. Keep ids stable and row labels complete.
- Use series in chartPalette order; mark comparisons with comparison=true and supply direct labels or patterns for more than four series.
- Put values and labels on neutral surfaces. Compose metrics with the full DataTrend block and goals with Progress.
- Keep prior content while refreshing. Use a delayed Skeleton only for a first load.
- Label sample datasets as illustrative and derive every chart, metric and table on a screen from the same rows.

### Không nên

- Do not pick arbitrary hues, apply color alpha, add opacity steps or animate chart drawing.
- Do not connect across missing values, clamp invalid facts or treat null as zero.
- Do not average unequal-duration availability samples or count status cells as uptime.
- Do not imply that cohort heat bands are success thresholds.
- Do not add a second Card surface around a chart already inside a Card.

## Props

| Tên | Kiểu | Giá trị | Mặc định | Mô tả |
| --- | --- | --- | --- | --- |
| `type` (bắt buộc) | `enum` | `line`, `area`, `bar`, `sparkline`, `composition`, `donut`, `funnel`, `timeline`, `cohort`, `uptime` |  | Required discriminant. Each type accepts only its own data shape. |
| `label` (bắt buộc) | `string` |  |  | Required accessible chart name. |
| `description` | `string` |  |  | Optional context associated with the chart. |
| `data` (bắt buộc) | `ChartRow[] \| ChartItem[] \| ChartRange[] \| ChartCohortRow[] \| ChartUptimeRow[]` |  |  | Ordered local data matching type. Null preserves missing or unobserved meaning; invalid values are reported. |
| `series` | `ChartSeries[]` |  |  | Required for line, area, bar and sparkline. Stable ids map to values; comparison adds a dashed stroke. Sparkline takes one series. |
| `height` | `number` |  |  | Plot height in CSS pixels. Defaults to 256, sparkline 48, compact bar 32. Timeline, cohort and uptime size to their rows by default; a height fixes the timeline and caps cohort and uptime, which then scroll. |
| `legend` | `boolean` |  | `true` | Show the series or status legend. Defaults true except sparkline and single-series bar. Composition, donut and funnel keep direct labels without a duplicate legend. |
| `interactive` | `boolean` |  | `true` | Enable pointer, touch and keyboard inspection. Defaults true except sparkline. |
| `pending` | `boolean` |  | `false` | Retain current data, mark the figure busy and dim only the plot. |
| `table` | `enum` | `toggle`, `visible`, `hidden` | `toggle` | Toggle reveals the semantic data view. Hidden keeps the table accessible with visually hidden presentation. Sparkline defaults hidden. |
| `locale` | `string` |  | `en` | Explicit number-formatting locale shared by server and client. |
| `labels` | `Partial<ChartLabels>` |  |  | Override viewData, hideData, loading, empty, missing, unobserved, invalid, noSeries, zeroTotal, value, total, cohortSize, conversion, share, coverage, success, warning, danger, unknown, neutral, start, end, status and point text. Raw values use formatValue; derived percentages always use locale-aware percentage formatting. |
| `formatValue` | `(value: number, id: string) => string` |  |  | Format a finite number and stable series or item id without changing geometry. |
| `xScale` | `enum` | `category`, `linear`, `time` | `category` | Cartesian axis spacing. Numeric and time modes require finite, strictly ascending x values; time uses epoch milliseconds. Without formatX, time positions show a short UTC date. |
| `formatX` | `(value: number) => string` |  |  | Format numeric or time ticks for Cartesian charts and timeline; full row labels remain available. |
| `domain` | `[number, number]` |  |  | Cartesian finite ascending value bounds containing every value. Bar domains must include zero. |
| `axes` | `boolean` |  | `true` | Show Cartesian axes. Defaults true except sparkline and compact bar. |
| `grid` | `boolean` |  | `true` | Show Cartesian grid lines. Defaults true except sparkline and compact bar. |
| `hiddenSeries` | `string[]` |  |  | Controlled hidden Cartesian series ids. Palette positions remain stable. |
| `defaultHiddenSeries` | `string[]` |  |  | Uncontrolled initial hidden Cartesian series ids. |
| `onHiddenSeriesChange` | `(ids: string[]) => void` |  |  | Receive the hidden series ids after a legend action. |
| `stack` | `enum` | `none`, `normal` | `none` | Area only: overlaid independent series or a nonnegative summed stack. Null breaks the stack at that row. |
| `orientation` | `enum` | `vertical`, `horizontal` | `vertical` | Bar only: vertical or horizontal bars. |
| `layout` | `enum` | `grouped`, `stacked`, `percentage` | `grouped` | Bar only: grouped, signed stacked or nonnegative percentage composition. Percentage rows with zero totals stay empty. |
| `compact` | `boolean` |  | `false` | Bar only: short numeric cell display without axes or legend. A shared domain gives comparable lengths. |
| `range` | `[number, number]` |  |  | Timeline only, required finite ascending range in caller-defined units. Every entry must fit. |
| `marker` | `{ value: number; label: string }` |  |  | Optional timeline reference position. Outside-range positions remain described without a visual marker. |
| `columns` | `Array<{ id: string; label: string }>` |  |  | Cohort only, required unique columns. Each row has one percentage or null per column. |
| `thresholds` | `[number, number, number, number]` |  |  | Cohort only: four ascending bounds inside (0, 100), defining five ordered heat bands of chart series 1 that grow stronger with each band; the value prints on the cell. Defaults [20, 40, 60, 80]. |

## Cấu tạo

| Phần | Mô tả |
| --- | --- |
| `root` | Named figure with description and loading state. |
| `plot` | Responsive plot and one keyboard inspection surface. Lines and area edges are smooth monotone curves that never overshoot a value; area fills fade from the series color at opacity-subtle to transparent. Grid lines are dashed and quiet; the zero line turns solid on signed domains. Bars are slim, round only their value end and never get outlines. Composition parts and donut sectors are separated by a 2px gap instead of an outline. Inspected line and area points use their series fill, a white 2px color-border-chart-marker ring and drop-shadow-low. The inspected composition part grows 4px above and below the track, and the inspected donut sector grows 4px outward, drawn above its neighbors. |
| `legend` | Series visibility buttons with compact keys (a short stroke for lines, a small swatch for filled marks) or a static status list with status icons. Composition and donut list each category with its amount and share; funnel rows show the conversion from the previous stage, the amount and the share of the first stage, and every stage uses series 1, since stages are one measure. |
| `tooltip` | Compact inspected values beside the pointer or keyboard-selected mark, bounded inside the plot and rounded with radius-container. |
| `table` | Semantic raw-data view with caption and headers. |

## Khả năng truy cập

Role: `figure`

| Phím | Hành động |
| --- | --- |
| `Tab` | Enter the plot once; legend buttons and data toggle remain separate controls. |
| `Arrow keys` | Inspect rows and visible series; navigate ranges or matrix cells according to chart type. |
| `Home / End` | Inspect the first or last Cartesian row. |
| `Escape` | Close inspection and restore focus to the plot. |

- The required label names the figure; description supplies context. Every chart retains a semantic data table, including table=hidden.
- Null means missing for Cartesian values and not yet observed for cohorts. Zero is an observed value.
- Series retain palette identity when hidden. More than four series add patterns and dashes; with four or fewer, keep the legend or the data table visible, since a hidden legend leaves color as the only cue.
- Touch taps pin inspection; a second tap or outside tap dismisses it. Normal page scrolling remains available. Mouse hover never receives keyboard focus contours, and a focused plot keeps its focus ring while the mouse moves. Each bar group is one hit band across the value axis; the gaps between groups dismiss inspection. Uptime rows are 44px targets that pick the period under the pointer. In horizontal bars, Up and Down move between rows and Left and Right between series.
- Uptime samples represent equal-duration periods. Coverage and the mean of known availability remain distinct.

## Cài đặt

```bash
npx werewolf-ui add chart
```

Chạy `npx werewolf-ui init` một lần trong app trước khi thêm component. Init cài token, thêm CSS import và luật cho agent. Add cài component này cùng các dependency và giữ nguyên theme của bạn. Xem [Cài đặt](https://werewolf-ui.vercel.app/vi/docs/installation.md) để biết yêu cầu và cách cài qua registry.
