diff --git a/docs/docs/api/appkit-ui/data/AreaChart.mdx b/docs/docs/api/appkit-ui/data/AreaChart.mdx
index 59ce64da1..60596e002 100644
--- a/docs/docs/api/appkit-ui/data/AreaChart.mdx
+++ b/docs/docs/api/appkit-ui/data/AreaChart.mdx
@@ -6,25 +6,40 @@ Area Chart component for trend visualization with filled areas.
## Example
```tsx
-"use client";
-
import { AreaChart } from "@databricks/appkit-ui/react";
+// Long rows as `config/queries/revenue_by_channel.sql` returns them, one row
+// per month and channel; `seriesKey` turns each channel into a stacked band.
+// SELECT DATE_TRUNC('MONTH', order_date) AS month, channel,
+// CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY 1, 2 ORDER BY 1
+const rows = [
+ { month: "2026-01-01", channel: "Online", revenue: 412000 },
+ { month: "2026-01-01", channel: "Retail", revenue: 268000 },
+ { month: "2026-02-01", channel: "Online", revenue: 451000 },
+ { month: "2026-02-01", channel: "Retail", revenue: 259000 },
+ { month: "2026-03-01", channel: "Online", revenue: 498000 },
+ { month: "2026-03-01", channel: "Retail", revenue: 281000 },
+ { month: "2026-04-01", channel: "Online", revenue: 530000 },
+ { month: "2026-04-01", channel: "Retail", revenue: 274000 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
+
export default function AreaChartExample() {
return (
);
@@ -37,11 +52,19 @@ export default function AreaChartExample() {
Area Chart component for trend visualization with filled areas.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** the split of a total changes over time (stacked), or for a running total.
+
+**Not when:** up to 12 periods (stacked BarChart); over 5 parts (top 4 plus "Other" in SQL); values of mixed sign.
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per period and part: long rows plus `seriesKey`, or one column per part.
+
+**Gotchas:** pass `stacked` for composition; unstacked areas overlap. A stack of mixed-sign values logs a warning.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/area/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/area/index.tsx)
@@ -54,33 +77,43 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
-| `orientation` | `"horizontal" \| "vertical"` | | `"vertical"` | Chart orientation |
+| `sparkline` | `boolean` | | - | A KPI-tile sparkline: no axes, legend or margins, the y range fitted to the data, a gap at missing values, and a dot when there is one point. Height defaults to 48 px. |
+| `symbolSize` | `number` | | `8` | Size of the data point symbols |
| `showSymbol` | `boolean` | | `false` | Show data point symbols |
-| `smooth` | `boolean` | | `true` | Smooth line curves |
+| `smooth` | `boolean` | | `true (false with `defaults="v3"`)` | Smooth line curves. |
+| `connectNulls` | `boolean` | | `false` | Draw the line across missing values instead of leaving a gap. Only applies with `defaults="v3"`, where missing values stay missing. |
| `stacked` | `boolean` | | `false` | Stack areas |
+| `referenceLines` | `ChartReferenceLine[]` | | - | Target or reference lines across the plot, at values of the value axis (`[{ value: 100, label: "Target" }]`). |
+| `zoom` | `boolean` | | `false` | Zoom along the category or time axis: mouse wheel and drag in the plot, plus a slider. Use it for long series. |
+| `series` | `Record` | | - | Per-`yKey` series type and value axis, for combo charts and a second y axis: `series={{ margin_pct: { type: "line", axis: "right" } }}` on a BarChart draws `margin_pct` as a line against its own axis. |
### Usage
```tsx
-import { AreaChart } from '@databricks/appkit-ui';
+import { AreaChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/BarChart.mdx b/docs/docs/api/appkit-ui/data/BarChart.mdx
index c016e9add..0e17b1aba 100644
--- a/docs/docs/api/appkit-ui/data/BarChart.mdx
+++ b/docs/docs/api/appkit-ui/data/BarChart.mdx
@@ -6,22 +6,35 @@ Bar Chart component for categorical comparisons.
## Example
```tsx
-"use client";
-
import { BarChart } from "@databricks/appkit-ui/react";
+// Rows as `config/queries/revenue_by_segment.sql` returns them:
+// SELECT segment, CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY segment ORDER BY revenue DESC LIMIT 10
+// In an app, pass the query instead of the rows:
+//
+const rows = [
+ { segment: "Enterprise", revenue: 1840500 },
+ { segment: "Mid-market", revenue: 1215300 },
+ { segment: "SMB", revenue: 864200 },
+ { segment: "Public sector", revenue: 512900 },
+ { segment: "Education", revenue: 301750 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
+
export default function BarChartExample() {
return (
);
@@ -34,11 +47,19 @@ export default function BarChartExample() {
Bar Chart component for categorical comparisons.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** comparing one measure across 3 to 15 categories, or across up to 12 periods.
+
+**Not when:** more than 15 categories (DataTable); more than 12 periods (LineChart); 2 to 5 parts of one whole (DonutChart); one category (a KPI tile).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per category, already sorted in SQL; a category column (text) and a measure column (number). Several series: one measure column each, or long rows plus `seriesKey`.
+
+**Gotchas:** categories keep their row order, numbers and years included (`xType="value"` sorts them). Pass `orientation` if the automatic rule picks the wrong one. Cast DECIMAL to DOUBLE in SQL, or pass the strings: both parse.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/bar/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/bar/index.tsx)
@@ -51,31 +72,40 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
-| `orientation` | `"horizontal" \| "vertical"` | | `"vertical"` | Chart orientation |
-| `stacked` | `boolean` | | - | Stack bars |
+| `orientation` | `"horizontal" \| "vertical"` | | - | Bar orientation. When unset, dates are vertical and category labels are horizontal. With `defaults="v3"`: dates, numbers (such as years) and up to 7 labels of at most 10 characters are vertical; anything else is horizontal. |
+| `stacked` | `boolean` | | `false` | Stack the series, on vertical and horizontal bars. |
+| `referenceLines` | `ChartReferenceLine[]` | | - | Target or reference lines across the plot, at values of the value axis (`[{ value: 100, label: "Target" }]`). |
+| `zoom` | `boolean` | | `false` | Zoom along the category or time axis: mouse wheel and drag in the plot, plus a slider. Use it for long series. |
+| `showValues` | `boolean` | | `false` | Print each bar's (or point's) value next to it. |
+| `series` | `Record` | | - | Per-`yKey` series type and value axis, for combo charts and a second y axis: `series={{ margin_pct: { type: "line", axis: "right" } }}` on a BarChart draws `margin_pct` as a line against its own axis. |
### Usage
```tsx
-import { BarChart } from '@databricks/appkit-ui';
+import { BarChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/DataTable.mdx b/docs/docs/api/appkit-ui/data/DataTable.mdx
index 00c4fb15f..95216b096 100644
--- a/docs/docs/api/appkit-ui/data/DataTable.mdx
+++ b/docs/docs/api/appkit-ui/data/DataTable.mdx
@@ -6,17 +6,37 @@ Production-ready data table with automatic data fetching and state management
## Example
```tsx
-"use client";
-
import { DataTable } from "@databricks/appkit-ui/react";
+// Detail rows with typed columns. In an app, pass the query instead of rows:
+//
+const rows = [
+ { order_id: "00412", customer: "Acme", amount: 1840.5, shipped: true },
+ { order_id: "00413", customer: "Globex", amount: 215.0, shipped: false },
+ { order_id: "00414", customer: "Initech", amount: 9310.25, shipped: true },
+ { order_id: "00415", customer: "Hooli", amount: null, shipped: false },
+];
+
+const usd = new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+});
+
export default function DataTableExample() {
return (
(value == null ? "—" : usd.format(Number(value))),
+ align: "right",
+ },
+ { key: "shipped" },
+ ]}
+ defaultSort={{ key: "amount", desc: true }}
pageSize={10}
/>
);
@@ -29,6 +49,15 @@ export default function DataTableExample() {
Production-ready data table with automatic data fetching and state management
+**Use when:** readers need the exact records (detail rows, a top N with a link column).
+
+**Not when:** one number (a KPI tile) or a trend (a chart). On a dashboard, pick at most 8 columns with `columns`.
+
+**Rows:** detail rows with aliased snake_case columns; pass `queryKey` or `data`.
+
+**Gotchas:** formats come from the values, so cast in SQL what should read as a number, and use `columns` for
+labels, money and percent formats, widths and link cells.
+
Features:
- Automatic column generation from data structure
- Integrated with useAnalyticsQuery for data fetching
@@ -38,11 +67,11 @@ Features:
- Responsive design
- Supports opinionated mode (auto columns) and full-control mode (`children(table)`)
-In opinionated mode the columns are the keys of the first row that match `/^[a-zA-Z_][a-zA-Z0-9_]*$/` (other
-keys are dropped), headed by the key in Title Case. Every cell whose value parses as a number, numeric strings
-included, is right-aligned and formatted: a key containing `cost`, `price`, `spend`, `revenue` or `usd` shows as
-USD, and any other value of 1000 or more is abbreviated (10021 shows as 10K). For ids, zip codes or years, render
-a `Table` from `useAnalyticsQuery` rows instead.
+In opinionated mode the columns are `columns` when given, otherwise every key of the first row, headed by the key
+in Title Case (a key such as `count(1)` is shown as written). Cells are formatted by the column's type, inferred from all
+of its values and never from its name: numbers (and numeric text such as DECIMAL strings) are right-aligned at full
+precision, with separators above four digits; text with a leading zero ("02134") stays text; booleans show as
+true/false; timestamps as `YYYY-MM-DD HH:MM:SS`; objects as JSON; null and empty values as a dash.
**Source:** [`packages/appkit-ui/src/react/table/data-table.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/table/data-table.tsx)
@@ -52,19 +81,29 @@ a `Table` from `useAnalyticsQuery` rows instead.
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
-| `queryKey` | `string` | ✓ | - | The query key to fetch the data |
-| `parameters` | `Record` | ✓ | - | The parameters to pass to the query |
-| `filterColumn` | `string` | | - | The column to filter by |
+| `queryKey` | `string` | | - | The query key to fetch the data |
+| `parameters` | `Record` | | - | The parameters to pass to the query. Optional, as on charts. |
+| `data` | `ChartDataInput` | | - | Rows to show, or an Arrow Table: the same contract as a chart's `data`. Use it for stub rows while building the UI, Lakebase rows, or a result already fetched with `useAnalyticsQuery` for a chart on the same screen. |
+| `loading` | `boolean` | | - | Show the loading state (data mode). |
+| `error` | `string \| Error \| null` | | - | Show an error state (data mode). |
+| `defaultSort` | `DataTableSort` | | - | Initial sort, e.g. `{ key: "revenue", desc: true }`. Headers show the direction and set `aria-sort`. |
+| `columns` | `DataTableColumn[]` | | - | Columns to show, in order, with label, format, alignment, width and custom cell content. Defaults to every key of the first row with the format inferred from the values. |
+| `toolbar` | `boolean \| { search?: boolean; columns?: boolean; } \| undefined` | | `true` | The toolbar above the table: a search box and a Columns menu. `false` hides it; an object hides either part. |
+| `filterColumn` | `string` | | - | Filter only this column. Without it, the search box matches any column. |
| `filterPlaceholder` | `string` | | - | Optional placeholder for the filter input |
-| `transform` | `((data: any[]) => any[])` | | - | Optional function to transform data before creating table. A new function reference re-runs it and resets the table to the first page, so keep it stable: define it outside the component, or rely on the React Compiler (enabled in the AppKit template); without the compiler, wrap it in `useCallback`. |
+| `transform` | `((data: any[]) => any[])` | | - | Optional function to transform data before creating table (rows in, rows out). An inline function is fine: when it returns the same rows the table keeps its page and columns. |
+| `transformer` | `((data: any[]) => any[])` | | - | Same as `transform`, under the name charts use. |
| `labels` | `DataTableLabels` | | - | Optional labels for the DataTable component |
| `ariaLabel` | `string` | | - | Optional accessibility label for the DataTable component |
| `testId` | `string` | | - | Optional test ID for the DataTable component |
| `className` | `string` | | - | Optional CSS class name for the DataTable component |
| `enableRowSelection` | `boolean` | | - | Enable row selection with checkboxes |
-| `onRowSelectionChange` | `((rowSelection: RowSelectionState) => void)` | | - | Callback function to handle row selection changes |
+| `onRowSelectionChange` | `((rowSelection: RowSelectionState) => void)` | | - | Callback function to handle row selection changes (TanStack index map; prefer `onSelectionChange`) |
+| `onSelectionChange` | `((rows: any[]) => void)` | | - | Called with the selected rows themselves whenever the selection changes. Needs `enableRowSelection`. Rows are selected by position, so a new `data` array clears the selection. Memoize `data` to keep it across renders. |
+| `onRowClick` | `((row: any) => void)` | | - | Called with the row when a row is clicked, or activated with Enter. Rows become focusable. |
| `children` | `((table: Table) => ReactNode)` | | - | Optional children for full control mode |
| `pageSize` | `number` | | - | Number of rows to display per page |
+| `maxHeight` | `string \| number` | | `600` | Height at which the table body scrolls (pixels or a CSS length), with the header kept in view. |
| `pageSizeOptions` | `number[]` | | - | Options for the page size selector |
@@ -72,7 +111,7 @@ a `Table` from `useAnalyticsQuery` rows instead.
### Usage
```tsx
-import { DataTable } from '@databricks/appkit-ui';
+import { DataTable } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/DonutChart.mdx b/docs/docs/api/appkit-ui/data/DonutChart.mdx
index 42bed7fb6..f1e577b3d 100644
--- a/docs/docs/api/appkit-ui/data/DonutChart.mdx
+++ b/docs/docs/api/appkit-ui/data/DonutChart.mdx
@@ -6,19 +6,25 @@ Donut Chart component (Pie chart with inner radius).
## Example
```tsx
-"use client";
-
import { DonutChart } from "@databricks/appkit-ui/react";
+// Headcount by department, with the total in the hole.
+// SELECT department, COUNT(*) AS headcount FROM employees
+// GROUP BY department ORDER BY headcount DESC
+const rows = [
+ { department: "Engineering", headcount: 450 },
+ { department: "Sales", headcount: 300 },
+ { department: "Marketing", headcount: 250 },
+ { department: "Operations", headcount: 200 },
+];
+
export default function DonutChartExample() {
return (
);
@@ -31,11 +37,19 @@ export default function DonutChartExample() {
Donut Chart component (Pie chart with inner radius).
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** 2 to 5 parts of one whole, with the total in the hole (`centerLabel`).
+
+**Not when:** 6 or more parts, or parts of similar size (horizontal BarChart); negative values (BarChart).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per part, sorted descending: a name column and a value column. Pass both keys.
+
+**Gotchas:** `innerRadius` is clamped to 63; `innerRadius={0}` draws a pie.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/pie/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/pie/index.tsx)
@@ -48,32 +62,38 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
-| `innerRadius` | `number` | | `0` | Inner radius for donut charts (0-100%) |
-| `showLabels` | `boolean` | | `true` | Show labels on slices |
+| `innerRadius` | `number` | | `0 (40 on DonutChart)` | Hole radius in percent of the chart, clamped to 0 to 63 (90% of the outer radius). `0` draws a plain pie, also on DonutChart. |
+| `showLabels` | `boolean` | | `true (false with `defaults="v3"`, where the legend shows name, value and share)` | Show labels on slices. |
| `labelPosition` | `"center" \| "outside" \| "inside"` | | `"outside"` | Label position |
+| `centerLabel` | `string \| boolean` | | `true on a v3 DonutChart` | Text in the donut hole, sized to fit it. `true` shows the formatted total (compacted, e.g. "9.7M", when the full number doesn't fit). Ignored on a pie without a hole. |
### Usage
```tsx
-import { DonutChart } from '@databricks/appkit-ui';
+import { DonutChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/HeatmapChart.mdx b/docs/docs/api/appkit-ui/data/HeatmapChart.mdx
index 48a959935..e9c424681 100644
--- a/docs/docs/api/appkit-ui/data/HeatmapChart.mdx
+++ b/docs/docs/api/appkit-ui/data/HeatmapChart.mdx
@@ -6,31 +6,31 @@ Heatmap Chart component for matrix-style data visualization.
## Example
```tsx
-"use client";
-
import { HeatmapChart } from "@databricks/appkit-ui/react";
-export default function HeatmapChartExample() {
- const data = [];
- const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
- const hours = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"];
-
- for (const day of days) {
- for (const hour of hours) {
- data.push({
- day,
- hour,
- count: Math.floor(Math.random() * 100),
- });
- }
- }
+// One row per cell, as `config/queries/orders_by_hour.sql` returns them.
+// Weekdays are put in calendar order whatever the row order.
+// SELECT DATE_FORMAT(created_at, 'E') AS weekday, HOUR(created_at) AS hour,
+// COUNT(*) AS orders
+// FROM orders GROUP BY 1, 2
+const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
+const hours = [8, 10, 12, 14, 16, 18];
+const rows = weekdays.flatMap((weekday, d) =>
+ hours.map((hour, h) => ({
+ weekday,
+ hour,
+ // Busy at lunch and on weekdays: a fixed pattern, not random data.
+ orders: (d < 5 ? 60 : 25) + (h === 2 ? 40 : 0) + ((d * 7 + h * 3) % 11),
+ })),
+);
+export default function HeatmapChartExample() {
return (
);
@@ -43,16 +43,24 @@ export default function HeatmapChartExample() {
Heatmap Chart component for matrix-style data visualization.
+**Use when:** finding where a measure is high or low across two dimensions (weekday by hour, cohort by period).
+
+**Not when:** under 3 by 3 cells (grouped BarChart); over 30 columns (aggregate in SQL).
+
+**Rows:** one per cell; name the roles with `columnKey`, `rowKey` and `valueKey`.
+
+**Gotchas:** repeated cells are summed with a warning; weekdays, months, numbers and dates are put in order (`xOrder`/`yOrder` override). Use `colorPalette="diverging"` for values around 0.
+
**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
Data should be in "long format" with three fields:
-- xKey: X-axis category (columns)
-- yAxisKey: Y-axis category (rows)
-- yKey: The numeric value for each cell
-
-Supports both query mode (queryKey + parameters) and data mode (static data).
+- columnKey (or xKey): X-axis category (columns)
+- rowKey (or yAxisKey): Y-axis category (rows)
+- valueKey (or yKey): The numeric value for each cell
**Source:** [`packages/appkit-ui/src/react/charts/heatmap/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/heatmap/index.tsx)
@@ -65,33 +73,43 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
| `yAxisKey` | `string` | | - | Field key for the Y-axis categories. For heatmaps, data should have: xKey (column), yAxisKey (row), and yKey (value). |
| `min` | `number` | | - | Min value for color scale (auto-detected if not provided) |
| `max` | `number` | | - | Max value for color scale (auto-detected if not provided) |
-| `showLabels` | `boolean` | | `false` | Show value labels on cells |
+| `showLabels` | `boolean` | | - | Show value labels on cells. Unset: on for up to 100 cells when each cell is wide enough for a label. |
+| `xOrder` | `readonly (string \| number)[]` | | - | Column order: these values first, in this order. Unset: weekdays and months in calendar order, numbers ascending, dates chronologically, other text in row order. |
+| `yOrder` | `readonly (string \| number)[]` | | - | Row order, as HeatmapChartSpecificProps.xOrder. |
+| `columnKey` | `string` | | - | The column dimension; same as `xKey`. |
+| `rowKey` | `string` | | - | The row dimension; same as `yAxisKey`. |
+| `valueKey` | `string` | | - | The numeric cell value; same as `yKey`. |
### Usage
```tsx
-import { HeatmapChart } from '@databricks/appkit-ui';
+import { HeatmapChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/LineChart.mdx b/docs/docs/api/appkit-ui/data/LineChart.mdx
index eaa662d00..dd61f4c16 100644
--- a/docs/docs/api/appkit-ui/data/LineChart.mdx
+++ b/docs/docs/api/appkit-ui/data/LineChart.mdx
@@ -6,24 +6,31 @@ Line Chart component for time-series and trend visualization.
## Example
```tsx
-"use client";
-
import { LineChart } from "@databricks/appkit-ui/react";
+// Rows as `config/queries/daily_orders.sql` returns them: a DATE column and a
+// count, one row per day. A day with no data is null and shows as a gap with
+// `defaults="v3"`.
+// SELECT order_date, COUNT(*) AS orders FROM orders
+// WHERE order_date >= :start_date GROUP BY order_date ORDER BY order_date
+// In an app:
+const rows = [
+ { order_date: "2026-03-01", orders: 182 },
+ { order_date: "2026-03-02", orders: 205 },
+ { order_date: "2026-03-03", orders: 198 },
+ { order_date: "2026-03-04", orders: null },
+ { order_date: "2026-03-05", orders: 231 },
+ { order_date: "2026-03-06", orders: 264 },
+ { order_date: "2026-03-07", orders: 249 },
+];
+
export default function LineChartExample() {
return (
);
@@ -36,11 +43,19 @@ export default function LineChartExample() {
Line Chart component for time-series and trend visualization.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** a measure changes over time.
+
+**Not when:** under 4 periods (vertical BarChart); over 5 series (top 4 plus "Other" in SQL).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per period, a DATE or TIMESTAMP column and a measure; several series as one column each or long rows plus `seriesKey`.
+
+**Gotchas:** the x axis is a time axis only when every `xKey` value is a date. Missing values draw as 0 unless `defaults="v3"`, which leaves a gap. Lines are smoothed unless `smooth={false}` or `defaults="v3"`. For a KPI tile use `sparkline`.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/line/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/line/index.tsx)
@@ -53,32 +68,42 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
-| `orientation` | `"horizontal" \| "vertical"` | | `"vertical"` | Chart orientation |
+| `sparkline` | `boolean` | | - | A KPI-tile sparkline: no axes, legend or margins, the y range fitted to the data, a gap at missing values, and a dot when there is one point. Height defaults to 48 px. |
+| `symbolSize` | `number` | | `8` | Size of the data point symbols |
| `showSymbol` | `boolean` | | `false` | Show data point symbols |
-| `smooth` | `boolean` | | `true` | Smooth line curves |
+| `smooth` | `boolean` | | `true (false with `defaults="v3"`)` | Smooth line curves. |
+| `connectNulls` | `boolean` | | `false` | Draw the line across missing values instead of leaving a gap. Only applies with `defaults="v3"`, where missing values stay missing. |
+| `referenceLines` | `ChartReferenceLine[]` | | - | Target or reference lines across the plot, at values of the value axis (`[{ value: 100, label: "Target" }]`). |
+| `zoom` | `boolean` | | `false` | Zoom along the category or time axis: mouse wheel and drag in the plot, plus a slider. Use it for long series. |
+| `series` | `Record` | | - | Per-`yKey` series type and value axis, for combo charts and a second y axis: `series={{ margin_pct: { type: "line", axis: "right" } }}` on a BarChart draws `margin_pct` as a line against its own axis. |
### Usage
```tsx
-import { LineChart } from '@databricks/appkit-ui';
+import { LineChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/PieChart.mdx b/docs/docs/api/appkit-ui/data/PieChart.mdx
index 60def78b4..05b8e617a 100644
--- a/docs/docs/api/appkit-ui/data/PieChart.mdx
+++ b/docs/docs/api/appkit-ui/data/PieChart.mdx
@@ -6,22 +6,20 @@ Pie Chart component for proportional data visualization.
## Example
```tsx
-"use client";
-
import { PieChart } from "@databricks/appkit-ui/react";
+// Two to five parts of one whole, as `config/queries/tickets_by_priority.sql`
+// returns them. More parts, or parts of similar size, read better as a bar chart.
+// SELECT priority, COUNT(*) AS tickets FROM tickets GROUP BY priority ORDER BY tickets DESC
+const rows = [
+ { priority: "Low", tickets: 412 },
+ { priority: "Medium", tickets: 268 },
+ { priority: "High", tickets: 121 },
+ { priority: "Urgent", tickets: 37 },
+];
+
export default function PieChartExample() {
- return (
-
- );
+ return ;
}
```
@@ -31,11 +29,19 @@ export default function PieChartExample() {
Pie Chart component for proportional data visualization.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** 2 to 5 parts of one whole.
+
+**Not when:** 6 or more parts, or parts of similar size (horizontal BarChart); negative values (BarChart); change over time (AreaChart).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per part, sorted descending: a name column and a value column. Pass both keys.
+
+**Gotchas:** a negative value shows an error and an all-zero result the empty state. Zero and missing slices are left out.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/pie/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/pie/index.tsx)
@@ -48,32 +54,38 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
-| `innerRadius` | `number` | | `0` | Inner radius for donut charts (0-100%) |
-| `showLabels` | `boolean` | | `true` | Show labels on slices |
+| `innerRadius` | `number` | | `0 (40 on DonutChart)` | Hole radius in percent of the chart, clamped to 0 to 63 (90% of the outer radius). `0` draws a plain pie, also on DonutChart. |
+| `showLabels` | `boolean` | | `true (false with `defaults="v3"`, where the legend shows name, value and share)` | Show labels on slices. |
| `labelPosition` | `"center" \| "outside" \| "inside"` | | `"outside"` | Label position |
+| `centerLabel` | `string \| boolean` | | `true on a v3 DonutChart` | Text in the donut hole, sized to fit it. `true` shows the formatted total (compacted, e.g. "9.7M", when the full number doesn't fit). Ignored on a pie without a hole. |
### Usage
```tsx
-import { PieChart } from '@databricks/appkit-ui';
+import { PieChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/RadarChart.mdx b/docs/docs/api/appkit-ui/data/RadarChart.mdx
index 9bb102b65..4a61b6b3a 100644
--- a/docs/docs/api/appkit-ui/data/RadarChart.mdx
+++ b/docs/docs/api/appkit-ui/data/RadarChart.mdx
@@ -6,23 +6,36 @@ Radar Chart component for multi-dimensional data comparison.
## Example
```tsx
-"use client";
-
import { RadarChart } from "@databricks/appkit-ui/react";
+// One row per entity, on one 0-100 scale, as a SQL query returns it.
+// `metrics` names the spokes; `max` fixes the rim at 100.
+// SELECT region, availability, latency_score, error_score, cost_score
+// FROM region_scores
+const rows = [
+ {
+ region: "us-east",
+ availability: 98,
+ latency_score: 82,
+ error_score: 91,
+ cost_score: 64,
+ },
+ {
+ region: "eu-west",
+ availability: 95,
+ latency_score: 88,
+ error_score: 79,
+ cost_score: 72,
+ },
+];
+
export default function RadarChartExample() {
return (
);
@@ -35,11 +48,19 @@ export default function RadarChartExample() {
Radar Chart component for multi-dimensional data comparison.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** asked to show how one or two entities score on 4 to 8 metrics on one scale.
+
+**Not when:** metrics in different units (DataTable); more than 3 entities (grouped BarChart).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per entity as SQL returns them, with `metrics` naming the spokes; or one row per metric with a `yKey` per entity.
+
+**Gotchas:** pass `max` when the scale is known (`max={100}` for scores). Negative values show an error.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/radar/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/radar/index.tsx)
@@ -52,30 +73,37 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
| `showArea` | `boolean` | | `true` | Show area fill |
+| `max` | `number \| readonly number[]` | | - | The rim value: one number for every metric (e.g. `100` for scores), or one per metric in row order. Unset: the data's largest value rounded up. |
+| `metrics` | `readonly string[]` | | - | Metric columns, for data with one row per entity (the shape a SQL query returns: `name, speed, power, range`). Each listed column becomes a spoke and each row a polygon named by `xKey` (or the first text column). Without it, rows are metrics and `yKey` columns are the series. |
### Usage
```tsx
-import { RadarChart } from '@databricks/appkit-ui';
+import { RadarChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/data/ScatterChart.mdx b/docs/docs/api/appkit-ui/data/ScatterChart.mdx
index 0e395190a..6c9378f51 100644
--- a/docs/docs/api/appkit-ui/data/ScatterChart.mdx
+++ b/docs/docs/api/appkit-ui/data/ScatterChart.mdx
@@ -6,25 +6,28 @@ Scatter Chart component for correlation and distribution visualization.
## Example
```tsx
-"use client";
-
import { ScatterChart } from "@databricks/appkit-ui/react";
+// Two measures per entity, as `config/queries/customer_health.sql` returns them.
+// Pass both keys: a scatter needs a numeric x and y.
+// SELECT customer, CAST(monthly_spend AS DOUBLE) AS monthly_spend, uptime_pct
+// FROM customer_health
+const rows = [
+ { customer: "Acme", monthly_spend: 5200, uptime_pct: 99.1 },
+ { customer: "Globex", monthly_spend: 5850, uptime_pct: 98.4 },
+ { customer: "Initech", monthly_spend: 5400, uptime_pct: 97.2 },
+ { customer: "Umbrella", monthly_spend: 6000, uptime_pct: 99.5 },
+ { customer: "Hooli", monthly_spend: 5050, uptime_pct: 98.9 },
+ { customer: "Stark", monthly_spend: 5600, uptime_pct: 97.8 },
+];
+
export default function ScatterChartExample() {
return (
`${value}%`}
height={300}
/>
);
@@ -37,11 +40,19 @@ export default function ScatterChartExample() {
Scatter Chart component for correlation and distribution visualization.
-**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+**Use when:** checking whether two measures are related, one point per entity.
+
+**Not when:** under 10 points (DataTable); over 2,000 points (aggregate in SQL first).
-**Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+**Rows:** one per entity: two numeric measures and a label column. Pass both `xKey` and `yKey`.
+
+**Gotchas:** a text x shows an error; DATE values on x give a time axis. A point with a missing x or y is left out.
+
+**Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
-Supports both query mode (queryKey + parameters) and data mode (static data).
+**Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+the UI is built first; add `loading` and `error` so the chart shows those states in its box.
**Source:** [`packages/appkit-ui/src/react/charts/scatter/index.tsx`](https://github.com/databricks/appkit/blob/main/packages/appkit-ui/src/react/charts/scatter/index.tsx)
@@ -54,30 +65,37 @@ Supports both query mode (queryKey + parameters) and data mode (static data).
| `queryKey` | `string` | | - | Analytics query key registered with analytics plugin |
| `parameters` | `Record` | | - | Query parameters passed to the analytics endpoint |
| `format` | `"auto" \| "json_array" \| "arrow_stream" \| "json" \| "arrow"` | | `"auto"` | Data format to use - "json_array": Use JSON format (smaller payloads, simpler) - "arrow_stream": Use Arrow format (faster for large datasets) - "auto": Automatically select based on expected data size |
-| `transformer` | `((data: T) => T)` | | - | Transform raw data before rendering |
+| `transformer` | `ChartTransformer` | | - | Reshape the fetched rows before rendering. See ChartTransformer. |
| `data` | `ChartDataInput` | | - | Arrow Table or an array of row objects (interfaces and `as const` arrays too). |
+| `loading` | `boolean` | | - | Show the loading state instead of the chart, in the chart's box. Use it while the rows are being fetched (`data={rows ?? []} loading={!rows}`). |
+| `error` | `string \| Error \| null` | | - | Show this error instead of the chart, in the chart's box. |
| `title` | `string` | | - | Chart title |
-| `showLegend` | `boolean` | | - | Show legend |
+| `showLegend` | `boolean` | | `true` | Show the legend. Series charts draw it only when there are two or more series; pie and donut always; on a heatmap it is the color scale. |
| `colorPalette` | `"categorical" \| "sequential" \| "diverging"` | | - | Color palette to use. Auto-selected based on chart type if not specified. - "categorical": Distinct colors for different categories (bar, pie, line) - "sequential": Gradient for magnitude/intensity (heatmap) - "diverging": Two-tone for positive/negative values |
-| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette) as hex, `rgb()` or `hsl()` strings, since ECharts draws on a canvas and cannot resolve `var()` or parse `oklch()` (those draw gray); without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes), held to the same formats. |
-| `height` | `number` | | - | Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). |
+| `colors` | `string[]` | | - | Custom colors for series (overrides colorPalette): hex, `rgb()` or `hsl()` strings, or theme tokens such as `var(--chart-cat-1)`, which are resolved against the root element before drawing (and again on theme change). Without it, series colors are the CSS variables `--chart-cat-1` to `--chart-cat-8` on `:root` (`--chart-seq-*` and `--chart-div-*` for the sequential and diverging palettes). ECharts can't parse `oklch()`, so the variables must hold hex, rgb or hsl values. |
+| `height` | `number` | | - | Chart height in pixels. Without it the chart fills its parent, at least 160 px (300 px with `defaults="v3"`). A className height such as `h-[400px]` also works. |
| `className` | `string` | | - | Additional CSS classes |
| `xKey` | `string` | | - | X-axis field key. Auto-detected from schema if not provided. |
| `yKey` | `string \| string[]` | | - | Y-axis field key(s). Auto-detected from schema if not provided. |
+| `seriesKey` | `string` | | - | Column that names the series in long rows (one row per x, series and value, as SQL returns them). With it, `yKey` is the single value column and each distinct value of `seriesKey` becomes a series. |
+| `xType` | `"time" \| "value" \| "category"` | | - | X axis type (cartesian charts). Inferred from the `xKey` values only, never from column names: all dates gives `"time"`, otherwise `"category"`. |
+| `defaults` | `"v3"` | | - | Opt into the v3 defaults. See ChartDefaults. Bug fixes apply with or without it; only defaults that change the look of a correct chart are gated. |
| `ariaLabel` | `string` | | - | Accessibility label for screen readers |
| `testId` | `string` | | - | Test ID for automated testing |
-| `options` | `Record` | | - | Additional ECharts options to merge |
+| `options` | `Record \| ((built: Record) => Record)` | | - | Additional ECharts options. An object is deep-merged into the built option (`series`, `xAxis`, `yAxis` and `grid` entry by entry, so a patch for the first series keeps its data). A function receives the built option and returns the option to render. |
| `valueFormatter` | `ChartValueFormatter` | | - | `(value: string \| number, field: string) => string`. Formats measure values in the chart's built-in value axes, tooltips, and value labels. `field` is the corresponding `yKey`, so one formatter can select a different format for each series. |
| `onDataClick` | `((datum: ChartClickDatum) => void)` | | - | Pointer-only: charts render to <canvas>, so this does not fire for keyboard users. Provide a keyboard-accessible equivalent (e.g. a table row action) for the same action. |
| `selected` | `string \| string[]` | | - | Controlled selection by category name. Matching data element(s) render at full prominence while the rest are dimmed. Drive it from your own state to reflect a cross-filter or selection. Categorical charts (bar, pie/donut) show emphasis; other chart types ignore it. |
| `symbolSize` | `number` | | `8` | Symbol size |
+| `referenceLines` | `ChartReferenceLine[]` | | - | Target or reference lines across the plot, at values of the value axis (`[{ value: 100, label: "Target" }]`). |
+| `showValues` | `boolean` | | `false` | Print each bar's (or point's) value next to it. |
### Usage
```tsx
-import { ScatterChart } from '@databricks/appkit-ui';
+import { ScatterChart } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/files/DirectoryList.mdx b/docs/docs/api/appkit-ui/files/DirectoryList.mdx
index d73e97ca3..46cad416a 100644
--- a/docs/docs/api/appkit-ui/files/DirectoryList.mdx
+++ b/docs/docs/api/appkit-ui/files/DirectoryList.mdx
@@ -34,7 +34,7 @@ Card-wrapped directory listing with loading, error, and empty states
### Usage
```tsx
-import { DirectoryList } from '@databricks/appkit-ui';
+import { DirectoryList } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/files/FileBreadcrumb.mdx b/docs/docs/api/appkit-ui/files/FileBreadcrumb.mdx
index e4b6bf5c5..b0cc17186 100644
--- a/docs/docs/api/appkit-ui/files/FileBreadcrumb.mdx
+++ b/docs/docs/api/appkit-ui/files/FileBreadcrumb.mdx
@@ -25,7 +25,7 @@ Path-aware breadcrumb navigation built on top of Breadcrumb primitives
### Usage
```tsx
-import { FileBreadcrumb } from '@databricks/appkit-ui';
+import { FileBreadcrumb } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/files/FileEntry.mdx b/docs/docs/api/appkit-ui/files/FileEntry.mdx
index 6b8e2ba15..deb640a1d 100644
--- a/docs/docs/api/appkit-ui/files/FileEntry.mdx
+++ b/docs/docs/api/appkit-ui/files/FileEntry.mdx
@@ -25,7 +25,7 @@ Single file or directory row with icon, name, size, and selection state
### Usage
```tsx
-import { FileEntry } from '@databricks/appkit-ui';
+import { FileEntry } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/files/FilePreviewPanel.mdx b/docs/docs/api/appkit-ui/files/FilePreviewPanel.mdx
index 2c594781f..0e453318e 100644
--- a/docs/docs/api/appkit-ui/files/FilePreviewPanel.mdx
+++ b/docs/docs/api/appkit-ui/files/FilePreviewPanel.mdx
@@ -30,7 +30,7 @@ Preview panel displaying file metadata, image/text preview, and download/delete
### Usage
```tsx
-import { FilePreviewPanel } from '@databricks/appkit-ui';
+import { FilePreviewPanel } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/files/NewFolderInput.mdx b/docs/docs/api/appkit-ui/files/NewFolderInput.mdx
index 56768e4a3..59fd688df 100644
--- a/docs/docs/api/appkit-ui/files/NewFolderInput.mdx
+++ b/docs/docs/api/appkit-ui/files/NewFolderInput.mdx
@@ -28,7 +28,7 @@ Inline folder-name input with create/cancel actions
### Usage
```tsx
-import { NewFolderInput } from '@databricks/appkit-ui';
+import { NewFolderInput } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/genie/GenieChat.mdx b/docs/docs/api/appkit-ui/genie/GenieChat.mdx
index 22e76deb6..40adb73d6 100644
--- a/docs/docs/api/appkit-ui/genie/GenieChat.mdx
+++ b/docs/docs/api/appkit-ui/genie/GenieChat.mdx
@@ -41,7 +41,7 @@ Full-featured chat interface for a single Databricks AI/BI Genie space. Handles
### Usage
```tsx
-import { GenieChat } from '@databricks/appkit-ui';
+import { GenieChat } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/genie/GenieChatInput.mdx b/docs/docs/api/appkit-ui/genie/GenieChatInput.mdx
index 79a6e6ab5..1f859d589 100644
--- a/docs/docs/api/appkit-ui/genie/GenieChatInput.mdx
+++ b/docs/docs/api/appkit-ui/genie/GenieChatInput.mdx
@@ -25,7 +25,7 @@ Auto-expanding textarea input with a send button for chat messages. Submits on E
### Usage
```tsx
-import { GenieChatInput } from '@databricks/appkit-ui';
+import { GenieChatInput } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/genie/GenieChatMessage.mdx b/docs/docs/api/appkit-ui/genie/GenieChatMessage.mdx
index 1092051c3..c2dbc541f 100644
--- a/docs/docs/api/appkit-ui/genie/GenieChatMessage.mdx
+++ b/docs/docs/api/appkit-ui/genie/GenieChatMessage.mdx
@@ -23,7 +23,7 @@ Renders a single Genie message bubble with optional expandable SQL query attachm
### Usage
```tsx
-import { GenieChatMessage } from '@databricks/appkit-ui';
+import { GenieChatMessage } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/genie/GenieChatMessageList.mdx b/docs/docs/api/appkit-ui/genie/GenieChatMessageList.mdx
index cb8d6d4b3..99f6742b7 100644
--- a/docs/docs/api/appkit-ui/genie/GenieChatMessageList.mdx
+++ b/docs/docs/api/appkit-ui/genie/GenieChatMessageList.mdx
@@ -26,7 +26,7 @@ Scrollable message list that renders Genie chat messages with auto-scroll, skele
### Usage
```tsx
-import { GenieChatMessageList } from '@databricks/appkit-ui';
+import { GenieChatMessageList } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/genie/GenieQueryVisualization.mdx b/docs/docs/api/appkit-ui/genie/GenieQueryVisualization.mdx
index 44dd3cd33..6e6a82cb5 100644
--- a/docs/docs/api/appkit-ui/genie/GenieQueryVisualization.mdx
+++ b/docs/docs/api/appkit-ui/genie/GenieQueryVisualization.mdx
@@ -30,7 +30,7 @@ Renders a chart + data table for a Genie query result.
### Usage
```tsx
-import { GenieQueryVisualization } from '@databricks/appkit-ui';
+import { GenieQueryVisualization } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Accordion.mdx b/docs/docs/api/appkit-ui/ui/Accordion.mdx
index 91620c343..f00d0ae14 100644
--- a/docs/docs/api/appkit-ui/ui/Accordion.mdx
+++ b/docs/docs/api/appkit-ui/ui/Accordion.mdx
@@ -37,7 +37,7 @@ Collapsible content sections organized in a vertical stack
### Usage
```tsx
-import { Accordion } from '@databricks/appkit-ui';
+import { Accordion } from '@databricks/appkit-ui/react';
```
@@ -63,7 +63,7 @@ Content area that expands and collapses within an accordion item
### Usage
```tsx
-import { AccordionContent } from '@databricks/appkit-ui';
+import { AccordionContent } from '@databricks/appkit-ui/react';
```
@@ -90,7 +90,7 @@ Individual collapsible section within an accordion
### Usage
```tsx
-import { AccordionItem } from '@databricks/appkit-ui';
+import { AccordionItem } from '@databricks/appkit-ui/react';
```
@@ -115,7 +115,7 @@ Clickable button that triggers accordion content visibility
### Usage
```tsx
-import { AccordionTrigger } from '@databricks/appkit-ui';
+import { AccordionTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Alert.mdx b/docs/docs/api/appkit-ui/ui/Alert.mdx
index 01772655f..620ed3362 100644
--- a/docs/docs/api/appkit-ui/ui/Alert.mdx
+++ b/docs/docs/api/appkit-ui/ui/Alert.mdx
@@ -29,7 +29,7 @@ Displays important information with optional icon and multiple variants
### Usage
```tsx
-import { Alert } from '@databricks/appkit-ui';
+import { Alert } from '@databricks/appkit-ui/react';
```
@@ -52,7 +52,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { AlertDescription } from '@databricks/appkit-ui';
+import { AlertDescription } from '@databricks/appkit-ui/react';
```
@@ -75,7 +75,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { AlertTitle } from '@databricks/appkit-ui';
+import { AlertTitle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/AlertDialog.mdx b/docs/docs/api/appkit-ui/ui/AlertDialog.mdx
index 79f54905d..148b220bc 100644
--- a/docs/docs/api/appkit-ui/ui/AlertDialog.mdx
+++ b/docs/docs/api/appkit-ui/ui/AlertDialog.mdx
@@ -31,7 +31,7 @@ Modal dialog that interrupts the user with critical information requiring immedi
### Usage
```tsx
-import { AlertDialog } from '@databricks/appkit-ui';
+import { AlertDialog } from '@databricks/appkit-ui/react';
```
@@ -56,7 +56,7 @@ Primary action button that confirms the alert
### Usage
```tsx
-import { AlertDialogAction } from '@databricks/appkit-ui';
+import { AlertDialogAction } from '@databricks/appkit-ui/react';
```
@@ -81,7 +81,7 @@ Cancel button that dismisses the alert dialog
### Usage
```tsx
-import { AlertDialogCancel } from '@databricks/appkit-ui';
+import { AlertDialogCancel } from '@databricks/appkit-ui/react';
```
@@ -111,7 +111,7 @@ Main content container for the alert dialog
### Usage
```tsx
-import { AlertDialogContent } from '@databricks/appkit-ui';
+import { AlertDialogContent } from '@databricks/appkit-ui/react';
```
@@ -136,7 +136,7 @@ Descriptive text explaining the alert
### Usage
```tsx
-import { AlertDialogDescription } from '@databricks/appkit-ui';
+import { AlertDialogDescription } from '@databricks/appkit-ui/react';
```
@@ -159,7 +159,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { AlertDialogFooter } from '@databricks/appkit-ui';
+import { AlertDialogFooter } from '@databricks/appkit-ui/react';
```
@@ -182,7 +182,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { AlertDialogHeader } from '@databricks/appkit-ui';
+import { AlertDialogHeader } from '@databricks/appkit-ui/react';
```
@@ -208,7 +208,7 @@ Background overlay that dims content behind the alert dialog
### Usage
```tsx
-import { AlertDialogOverlay } from '@databricks/appkit-ui';
+import { AlertDialogOverlay } from '@databricks/appkit-ui/react';
```
@@ -234,7 +234,7 @@ Portal container for rendering alert dialog content outside the DOM hierarchy
### Usage
```tsx
-import { AlertDialogPortal } from '@databricks/appkit-ui';
+import { AlertDialogPortal } from '@databricks/appkit-ui/react';
```
@@ -259,7 +259,7 @@ Title heading for the alert dialog
### Usage
```tsx
-import { AlertDialogTitle } from '@databricks/appkit-ui';
+import { AlertDialogTitle } from '@databricks/appkit-ui/react';
```
@@ -284,7 +284,7 @@ Button that triggers the alert dialog to open
### Usage
```tsx
-import { AlertDialogTrigger } from '@databricks/appkit-ui';
+import { AlertDialogTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/AspectRatio.mdx b/docs/docs/api/appkit-ui/ui/AspectRatio.mdx
index f601d239d..ee9197872 100644
--- a/docs/docs/api/appkit-ui/ui/AspectRatio.mdx
+++ b/docs/docs/api/appkit-ui/ui/AspectRatio.mdx
@@ -30,7 +30,7 @@ Container that maintains a specific aspect ratio for its content
### Usage
```tsx
-import { AspectRatio } from '@databricks/appkit-ui';
+import { AspectRatio } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Avatar.mdx b/docs/docs/api/appkit-ui/ui/Avatar.mdx
index 656858b26..4aabccc8c 100644
--- a/docs/docs/api/appkit-ui/ui/Avatar.mdx
+++ b/docs/docs/api/appkit-ui/ui/Avatar.mdx
@@ -29,7 +29,7 @@ Displays user profile picture or initials in a circular container
### Usage
```tsx
-import { Avatar } from '@databricks/appkit-ui';
+import { Avatar } from '@databricks/appkit-ui/react';
```
@@ -55,7 +55,7 @@ Fallback content displayed when avatar image fails to load
### Usage
```tsx
-import { AvatarFallback } from '@databricks/appkit-ui';
+import { AvatarFallback } from '@databricks/appkit-ui/react';
```
@@ -81,7 +81,7 @@ Image element for the avatar
### Usage
```tsx
-import { AvatarImage } from '@databricks/appkit-ui';
+import { AvatarImage } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Badge.mdx b/docs/docs/api/appkit-ui/ui/Badge.mdx
index ce2862fcd..37b52c339 100644
--- a/docs/docs/api/appkit-ui/ui/Badge.mdx
+++ b/docs/docs/api/appkit-ui/ui/Badge.mdx
@@ -30,7 +30,7 @@ Small label for displaying status, categories, or counts
### Usage
```tsx
-import { Badge } from '@databricks/appkit-ui';
+import { Badge } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Breadcrumb.mdx b/docs/docs/api/appkit-ui/ui/Breadcrumb.mdx
index c480562cb..6c0b19375 100644
--- a/docs/docs/api/appkit-ui/ui/Breadcrumb.mdx
+++ b/docs/docs/api/appkit-ui/ui/Breadcrumb.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Breadcrumb } from '@databricks/appkit-ui';
+import { Breadcrumb } from '@databricks/appkit-ui/react';
```
@@ -50,7 +50,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { BreadcrumbEllipsis } from '@databricks/appkit-ui';
+import { BreadcrumbEllipsis } from '@databricks/appkit-ui/react';
```
@@ -73,7 +73,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { BreadcrumbItem } from '@databricks/appkit-ui';
+import { BreadcrumbItem } from '@databricks/appkit-ui/react';
```
@@ -98,7 +98,7 @@ Clickable link within a breadcrumb item
### Usage
```tsx
-import { BreadcrumbLink } from '@databricks/appkit-ui';
+import { BreadcrumbLink } from '@databricks/appkit-ui/react';
```
@@ -121,7 +121,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { BreadcrumbList } from '@databricks/appkit-ui';
+import { BreadcrumbList } from '@databricks/appkit-ui/react';
```
@@ -144,7 +144,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { BreadcrumbPage } from '@databricks/appkit-ui';
+import { BreadcrumbPage } from '@databricks/appkit-ui/react';
```
@@ -167,7 +167,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { BreadcrumbSeparator } from '@databricks/appkit-ui';
+import { BreadcrumbSeparator } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Button.mdx b/docs/docs/api/appkit-ui/ui/Button.mdx
index 46835d345..0c47b4542 100644
--- a/docs/docs/api/appkit-ui/ui/Button.mdx
+++ b/docs/docs/api/appkit-ui/ui/Button.mdx
@@ -31,7 +31,7 @@ Clickable button with multiple variants and sizes
### Usage
```tsx
-import { Button } from '@databricks/appkit-ui';
+import { Button } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/ButtonGroup.mdx b/docs/docs/api/appkit-ui/ui/ButtonGroup.mdx
index bd518a5b7..165beceed 100644
--- a/docs/docs/api/appkit-ui/ui/ButtonGroup.mdx
+++ b/docs/docs/api/appkit-ui/ui/ButtonGroup.mdx
@@ -22,7 +22,7 @@ Container for grouping related buttons together with shared borders
### Usage
```tsx
-import { ButtonGroup } from '@databricks/appkit-ui';
+import { ButtonGroup } from '@databricks/appkit-ui/react';
```
@@ -49,7 +49,7 @@ Visual separator between buttons in a button group
### Usage
```tsx
-import { ButtonGroupSeparator } from '@databricks/appkit-ui';
+import { ButtonGroupSeparator } from '@databricks/appkit-ui/react';
```
@@ -74,7 +74,7 @@ Text label or content within a button group
### Usage
```tsx
-import { ButtonGroupText } from '@databricks/appkit-ui';
+import { ButtonGroupText } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Calendar.mdx b/docs/docs/api/appkit-ui/ui/Calendar.mdx
index 936180afe..ab428acbf 100644
--- a/docs/docs/api/appkit-ui/ui/Calendar.mdx
+++ b/docs/docs/api/appkit-ui/ui/Calendar.mdx
@@ -111,7 +111,7 @@ Date picker component for selecting single dates or date ranges
### Usage
```tsx
-import { Calendar } from '@databricks/appkit-ui';
+import { Calendar } from '@databricks/appkit-ui/react';
```
@@ -137,7 +137,7 @@ Individual day button within the calendar grid
### Usage
```tsx
-import { CalendarDayButton } from '@databricks/appkit-ui';
+import { CalendarDayButton } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Card.mdx b/docs/docs/api/appkit-ui/ui/Card.mdx
index c1c01e23a..1abf334b9 100644
--- a/docs/docs/api/appkit-ui/ui/Card.mdx
+++ b/docs/docs/api/appkit-ui/ui/Card.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Card } from '@databricks/appkit-ui';
+import { Card } from '@databricks/appkit-ui/react';
```
@@ -50,7 +50,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardAction } from '@databricks/appkit-ui';
+import { CardAction } from '@databricks/appkit-ui/react';
```
@@ -73,7 +73,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardContent } from '@databricks/appkit-ui';
+import { CardContent } from '@databricks/appkit-ui/react';
```
@@ -96,7 +96,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardDescription } from '@databricks/appkit-ui';
+import { CardDescription } from '@databricks/appkit-ui/react';
```
@@ -119,7 +119,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardFooter } from '@databricks/appkit-ui';
+import { CardFooter } from '@databricks/appkit-ui/react';
```
@@ -142,7 +142,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardHeader } from '@databricks/appkit-ui';
+import { CardHeader } from '@databricks/appkit-ui/react';
```
@@ -165,7 +165,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CardTitle } from '@databricks/appkit-ui';
+import { CardTitle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Carousel.mdx b/docs/docs/api/appkit-ui/ui/Carousel.mdx
index d54d884a8..b278fcf47 100644
--- a/docs/docs/api/appkit-ui/ui/Carousel.mdx
+++ b/docs/docs/api/appkit-ui/ui/Carousel.mdx
@@ -32,7 +32,7 @@ Slideshow component for cycling through content with navigation controls
### Usage
```tsx
-import { Carousel } from '@databricks/appkit-ui';
+import { Carousel } from '@databricks/appkit-ui/react';
```
@@ -55,7 +55,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CarouselContent } from '@databricks/appkit-ui';
+import { CarouselContent } from '@databricks/appkit-ui/react';
```
@@ -78,7 +78,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CarouselItem } from '@databricks/appkit-ui';
+import { CarouselItem } from '@databricks/appkit-ui/react';
```
@@ -105,7 +105,7 @@ Button to navigate to the next carousel slide
### Usage
```tsx
-import { CarouselNext } from '@databricks/appkit-ui';
+import { CarouselNext } from '@databricks/appkit-ui/react';
```
@@ -132,7 +132,7 @@ Button to navigate to the previous carousel slide
### Usage
```tsx
-import { CarouselPrevious } from '@databricks/appkit-ui';
+import { CarouselPrevious } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Checkbox.mdx b/docs/docs/api/appkit-ui/ui/Checkbox.mdx
index 63af8ac1f..f23125373 100644
--- a/docs/docs/api/appkit-ui/ui/Checkbox.mdx
+++ b/docs/docs/api/appkit-ui/ui/Checkbox.mdx
@@ -33,7 +33,7 @@ Checkbox input for selecting multiple options
### Usage
```tsx
-import { Checkbox } from '@databricks/appkit-ui';
+import { Checkbox } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Collapsible.mdx b/docs/docs/api/appkit-ui/ui/Collapsible.mdx
index 4af5130d6..4763e7d1b 100644
--- a/docs/docs/api/appkit-ui/ui/Collapsible.mdx
+++ b/docs/docs/api/appkit-ui/ui/Collapsible.mdx
@@ -33,7 +33,7 @@ Interactive component that expands and collapses content
### Usage
```tsx
-import { Collapsible } from '@databricks/appkit-ui';
+import { Collapsible } from '@databricks/appkit-ui/react';
```
@@ -59,7 +59,7 @@ Content area that can be expanded or collapsed
### Usage
```tsx
-import { CollapsibleContent } from '@databricks/appkit-ui';
+import { CollapsibleContent } from '@databricks/appkit-ui/react';
```
@@ -84,7 +84,7 @@ Button that toggles the collapsible content visibility
### Usage
```tsx
-import { CollapsibleTrigger } from '@databricks/appkit-ui';
+import { CollapsibleTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Command.mdx b/docs/docs/api/appkit-ui/ui/Command.mdx
index b882d5cfb..9ee0709d1 100644
--- a/docs/docs/api/appkit-ui/ui/Command.mdx
+++ b/docs/docs/api/appkit-ui/ui/Command.mdx
@@ -37,7 +37,7 @@ Command palette for keyboard-driven navigation and actions
### Usage
```tsx
-import { Command } from '@databricks/appkit-ui';
+import { Command } from '@databricks/appkit-ui/react';
```
@@ -69,7 +69,7 @@ Dialog wrapper for the command palette
### Usage
```tsx
-import { CommandDialog } from '@databricks/appkit-ui';
+import { CommandDialog } from '@databricks/appkit-ui/react';
```
@@ -94,7 +94,7 @@ Empty state displayed when no commands match the search
### Usage
```tsx
-import { CommandEmpty } from '@databricks/appkit-ui';
+import { CommandEmpty } from '@databricks/appkit-ui/react';
```
@@ -122,7 +122,7 @@ Group of related command items with an optional heading
### Usage
```tsx
-import { CommandGroup } from '@databricks/appkit-ui';
+import { CommandGroup } from '@databricks/appkit-ui/react';
```
@@ -149,7 +149,7 @@ Search input field for filtering command items
### Usage
```tsx
-import { CommandInput } from '@databricks/appkit-ui';
+import { CommandInput } from '@databricks/appkit-ui/react';
```
@@ -179,7 +179,7 @@ Individual selectable command item
### Usage
```tsx
-import { CommandItem } from '@databricks/appkit-ui';
+import { CommandItem } from '@databricks/appkit-ui/react';
```
@@ -205,7 +205,7 @@ Scrollable list container for command items
### Usage
```tsx
-import { CommandList } from '@databricks/appkit-ui';
+import { CommandList } from '@databricks/appkit-ui/react';
```
@@ -231,7 +231,7 @@ Visual separator between command groups
### Usage
```tsx
-import { CommandSeparator } from '@databricks/appkit-ui';
+import { CommandSeparator } from '@databricks/appkit-ui/react';
```
@@ -254,7 +254,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { CommandShortcut } from '@databricks/appkit-ui';
+import { CommandShortcut } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/ContextMenu.mdx b/docs/docs/api/appkit-ui/ui/ContextMenu.mdx
index dbdd45ba8..a4ba43eae 100644
--- a/docs/docs/api/appkit-ui/ui/ContextMenu.mdx
+++ b/docs/docs/api/appkit-ui/ui/ContextMenu.mdx
@@ -31,7 +31,7 @@ Menu triggered by right-clicking an element
### Usage
```tsx
-import { ContextMenu } from '@databricks/appkit-ui';
+import { ContextMenu } from '@databricks/appkit-ui/react';
```
@@ -59,7 +59,7 @@ import { ContextMenu } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuCheckboxItem } from '@databricks/appkit-ui';
+import { ContextMenuCheckboxItem } from '@databricks/appkit-ui/react';
```
@@ -97,7 +97,7 @@ import { ContextMenuCheckboxItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuContent } from '@databricks/appkit-ui';
+import { ContextMenuContent } from '@databricks/appkit-ui/react';
```
@@ -120,7 +120,7 @@ import { ContextMenuContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuGroup } from '@databricks/appkit-ui';
+import { ContextMenuGroup } from '@databricks/appkit-ui/react';
```
@@ -148,7 +148,7 @@ import { ContextMenuGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuItem } from '@databricks/appkit-ui';
+import { ContextMenuItem } from '@databricks/appkit-ui/react';
```
@@ -172,7 +172,7 @@ import { ContextMenuItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuLabel } from '@databricks/appkit-ui';
+import { ContextMenuLabel } from '@databricks/appkit-ui/react';
```
@@ -196,7 +196,7 @@ import { ContextMenuLabel } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuPortal } from '@databricks/appkit-ui';
+import { ContextMenuPortal } from '@databricks/appkit-ui/react';
```
@@ -221,7 +221,7 @@ import { ContextMenuPortal } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuRadioGroup } from '@databricks/appkit-ui';
+import { ContextMenuRadioGroup } from '@databricks/appkit-ui/react';
```
@@ -248,7 +248,7 @@ import { ContextMenuRadioGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuRadioItem } from '@databricks/appkit-ui';
+import { ContextMenuRadioItem } from '@databricks/appkit-ui/react';
```
@@ -271,7 +271,7 @@ import { ContextMenuRadioItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuSeparator } from '@databricks/appkit-ui';
+import { ContextMenuSeparator } from '@databricks/appkit-ui/react';
```
@@ -292,7 +292,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ContextMenuShortcut } from '@databricks/appkit-ui';
+import { ContextMenuShortcut } from '@databricks/appkit-ui/react';
```
@@ -317,7 +317,7 @@ import { ContextMenuShortcut } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuSub } from '@databricks/appkit-ui';
+import { ContextMenuSub } from '@databricks/appkit-ui/react';
```
@@ -355,7 +355,7 @@ import { ContextMenuSub } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuSubContent } from '@databricks/appkit-ui';
+import { ContextMenuSubContent } from '@databricks/appkit-ui/react';
```
@@ -381,7 +381,7 @@ import { ContextMenuSubContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuSubTrigger } from '@databricks/appkit-ui';
+import { ContextMenuSubTrigger } from '@databricks/appkit-ui/react';
```
@@ -405,7 +405,7 @@ import { ContextMenuSubTrigger } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ContextMenuTrigger } from '@databricks/appkit-ui';
+import { ContextMenuTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Dialog.mdx b/docs/docs/api/appkit-ui/ui/Dialog.mdx
index 7e226b205..5a2d9a392 100644
--- a/docs/docs/api/appkit-ui/ui/Dialog.mdx
+++ b/docs/docs/api/appkit-ui/ui/Dialog.mdx
@@ -32,7 +32,7 @@ Modal dialog that overlays the page content
### Usage
```tsx
-import { Dialog } from '@databricks/appkit-ui';
+import { Dialog } from '@databricks/appkit-ui/react';
```
@@ -57,7 +57,7 @@ Button that closes the dialog
### Usage
```tsx
-import { DialogClose } from '@databricks/appkit-ui';
+import { DialogClose } from '@databricks/appkit-ui/react';
```
@@ -90,7 +90,7 @@ Main content area of the dialog
### Usage
```tsx
-import { DialogContent } from '@databricks/appkit-ui';
+import { DialogContent } from '@databricks/appkit-ui/react';
```
@@ -115,7 +115,7 @@ Description text for the dialog
### Usage
```tsx
-import { DialogDescription } from '@databricks/appkit-ui';
+import { DialogDescription } from '@databricks/appkit-ui/react';
```
@@ -138,7 +138,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { DialogFooter } from '@databricks/appkit-ui';
+import { DialogFooter } from '@databricks/appkit-ui/react';
```
@@ -161,7 +161,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { DialogHeader } from '@databricks/appkit-ui';
+import { DialogHeader } from '@databricks/appkit-ui/react';
```
@@ -187,7 +187,7 @@ Dimmed overlay behind the dialog
### Usage
```tsx
-import { DialogOverlay } from '@databricks/appkit-ui';
+import { DialogOverlay } from '@databricks/appkit-ui/react';
```
@@ -213,7 +213,7 @@ Portal container for dialog content
### Usage
```tsx
-import { DialogPortal } from '@databricks/appkit-ui';
+import { DialogPortal } from '@databricks/appkit-ui/react';
```
@@ -238,7 +238,7 @@ Title text for the dialog
### Usage
```tsx
-import { DialogTitle } from '@databricks/appkit-ui';
+import { DialogTitle } from '@databricks/appkit-ui/react';
```
@@ -263,7 +263,7 @@ Button that opens the dialog
### Usage
```tsx
-import { DialogTrigger } from '@databricks/appkit-ui';
+import { DialogTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Drawer.mdx b/docs/docs/api/appkit-ui/ui/Drawer.mdx
index 5094a250d..65e62eca1 100644
--- a/docs/docs/api/appkit-ui/ui/Drawer.mdx
+++ b/docs/docs/api/appkit-ui/ui/Drawer.mdx
@@ -56,7 +56,7 @@ Draggable panel that slides in from screen edges
### Usage
```tsx
-import { Drawer } from '@databricks/appkit-ui';
+import { Drawer } from '@databricks/appkit-ui/react';
```
@@ -81,7 +81,7 @@ Button that closes the drawer
### Usage
```tsx
-import { DrawerClose } from '@databricks/appkit-ui';
+import { DrawerClose } from '@databricks/appkit-ui/react';
```
@@ -113,7 +113,7 @@ Main content area of the drawer
### Usage
```tsx
-import { DrawerContent } from '@databricks/appkit-ui';
+import { DrawerContent } from '@databricks/appkit-ui/react';
```
@@ -138,7 +138,7 @@ Description text for the drawer
### Usage
```tsx
-import { DrawerDescription } from '@databricks/appkit-ui';
+import { DrawerDescription } from '@databricks/appkit-ui/react';
```
@@ -161,7 +161,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { DrawerFooter } from '@databricks/appkit-ui';
+import { DrawerFooter } from '@databricks/appkit-ui/react';
```
@@ -184,7 +184,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { DrawerHeader } from '@databricks/appkit-ui';
+import { DrawerHeader } from '@databricks/appkit-ui/react';
```
@@ -210,7 +210,7 @@ Dimmed overlay behind the drawer
### Usage
```tsx
-import { DrawerOverlay } from '@databricks/appkit-ui';
+import { DrawerOverlay } from '@databricks/appkit-ui/react';
```
@@ -236,7 +236,7 @@ Portal container for drawer content
### Usage
```tsx
-import { DrawerPortal } from '@databricks/appkit-ui';
+import { DrawerPortal } from '@databricks/appkit-ui/react';
```
@@ -261,7 +261,7 @@ Title text for the drawer
### Usage
```tsx
-import { DrawerTitle } from '@databricks/appkit-ui';
+import { DrawerTitle } from '@databricks/appkit-ui/react';
```
@@ -286,7 +286,7 @@ Button that opens the drawer
### Usage
```tsx
-import { DrawerTrigger } from '@databricks/appkit-ui';
+import { DrawerTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/DropdownMenu.mdx b/docs/docs/api/appkit-ui/ui/DropdownMenu.mdx
index 85f57e5f6..1718e0555 100644
--- a/docs/docs/api/appkit-ui/ui/DropdownMenu.mdx
+++ b/docs/docs/api/appkit-ui/ui/DropdownMenu.mdx
@@ -33,7 +33,7 @@ Menu that displays when triggered by a button or element
### Usage
```tsx
-import { DropdownMenu } from '@databricks/appkit-ui';
+import { DropdownMenu } from '@databricks/appkit-ui/react';
```
@@ -61,7 +61,7 @@ import { DropdownMenu } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuCheckboxItem } from '@databricks/appkit-ui';
+import { DropdownMenuCheckboxItem } from '@databricks/appkit-ui/react';
```
@@ -102,7 +102,7 @@ import { DropdownMenuCheckboxItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuContent } from '@databricks/appkit-ui';
+import { DropdownMenuContent } from '@databricks/appkit-ui/react';
```
@@ -125,7 +125,7 @@ import { DropdownMenuContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuGroup } from '@databricks/appkit-ui';
+import { DropdownMenuGroup } from '@databricks/appkit-ui/react';
```
@@ -153,7 +153,7 @@ import { DropdownMenuGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuItem } from '@databricks/appkit-ui';
+import { DropdownMenuItem } from '@databricks/appkit-ui/react';
```
@@ -177,7 +177,7 @@ import { DropdownMenuItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuLabel } from '@databricks/appkit-ui';
+import { DropdownMenuLabel } from '@databricks/appkit-ui/react';
```
@@ -201,7 +201,7 @@ import { DropdownMenuLabel } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuPortal } from '@databricks/appkit-ui';
+import { DropdownMenuPortal } from '@databricks/appkit-ui/react';
```
@@ -226,7 +226,7 @@ import { DropdownMenuPortal } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuRadioGroup } from '@databricks/appkit-ui';
+import { DropdownMenuRadioGroup } from '@databricks/appkit-ui/react';
```
@@ -253,7 +253,7 @@ import { DropdownMenuRadioGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuRadioItem } from '@databricks/appkit-ui';
+import { DropdownMenuRadioItem } from '@databricks/appkit-ui/react';
```
@@ -276,7 +276,7 @@ import { DropdownMenuRadioItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuSeparator } from '@databricks/appkit-ui';
+import { DropdownMenuSeparator } from '@databricks/appkit-ui/react';
```
@@ -297,7 +297,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { DropdownMenuShortcut } from '@databricks/appkit-ui';
+import { DropdownMenuShortcut } from '@databricks/appkit-ui/react';
```
@@ -322,7 +322,7 @@ import { DropdownMenuShortcut } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuSub } from '@databricks/appkit-ui';
+import { DropdownMenuSub } from '@databricks/appkit-ui/react';
```
@@ -360,7 +360,7 @@ import { DropdownMenuSub } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuSubContent } from '@databricks/appkit-ui';
+import { DropdownMenuSubContent } from '@databricks/appkit-ui/react';
```
@@ -386,7 +386,7 @@ import { DropdownMenuSubContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuSubTrigger } from '@databricks/appkit-ui';
+import { DropdownMenuSubTrigger } from '@databricks/appkit-ui/react';
```
@@ -409,7 +409,7 @@ import { DropdownMenuSubTrigger } from '@databricks/appkit-ui';
### Usage
```tsx
-import { DropdownMenuTrigger } from '@databricks/appkit-ui';
+import { DropdownMenuTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Empty.mdx b/docs/docs/api/appkit-ui/ui/Empty.mdx
index 565d21359..016e02016 100644
--- a/docs/docs/api/appkit-ui/ui/Empty.mdx
+++ b/docs/docs/api/appkit-ui/ui/Empty.mdx
@@ -20,7 +20,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Empty } from '@databricks/appkit-ui';
+import { Empty } from '@databricks/appkit-ui/react';
```
@@ -41,7 +41,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { EmptyContent } from '@databricks/appkit-ui';
+import { EmptyContent } from '@databricks/appkit-ui/react';
```
@@ -62,7 +62,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { EmptyDescription } from '@databricks/appkit-ui';
+import { EmptyDescription } from '@databricks/appkit-ui/react';
```
@@ -83,7 +83,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { EmptyHeader } from '@databricks/appkit-ui';
+import { EmptyHeader } from '@databricks/appkit-ui/react';
```
@@ -106,7 +106,7 @@ import { EmptyHeader } from '@databricks/appkit-ui';
### Usage
```tsx
-import { EmptyMedia } from '@databricks/appkit-ui';
+import { EmptyMedia } from '@databricks/appkit-ui/react';
```
@@ -127,7 +127,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { EmptyTitle } from '@databricks/appkit-ui';
+import { EmptyTitle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Field.mdx b/docs/docs/api/appkit-ui/ui/Field.mdx
index d021a0001..401f8388a 100644
--- a/docs/docs/api/appkit-ui/ui/Field.mdx
+++ b/docs/docs/api/appkit-ui/ui/Field.mdx
@@ -22,7 +22,7 @@ Form field wrapper with label and input positioning
### Usage
```tsx
-import { Field } from '@databricks/appkit-ui';
+import { Field } from '@databricks/appkit-ui/react';
```
@@ -45,7 +45,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldContent } from '@databricks/appkit-ui';
+import { FieldContent } from '@databricks/appkit-ui/react';
```
@@ -68,7 +68,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldDescription } from '@databricks/appkit-ui';
+import { FieldDescription } from '@databricks/appkit-ui/react';
```
@@ -93,7 +93,7 @@ Error message display for invalid field values
### Usage
```tsx
-import { FieldError } from '@databricks/appkit-ui';
+import { FieldError } from '@databricks/appkit-ui/react';
```
@@ -116,7 +116,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldGroup } from '@databricks/appkit-ui';
+import { FieldGroup } from '@databricks/appkit-ui/react';
```
@@ -141,7 +141,7 @@ Label for a form field
### Usage
```tsx
-import { FieldLabel } from '@databricks/appkit-ui';
+import { FieldLabel } from '@databricks/appkit-ui/react';
```
@@ -166,7 +166,7 @@ Title or caption for a fieldset
### Usage
```tsx
-import { FieldLegend } from '@databricks/appkit-ui';
+import { FieldLegend } from '@databricks/appkit-ui/react';
```
@@ -189,7 +189,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldSeparator } from '@databricks/appkit-ui';
+import { FieldSeparator } from '@databricks/appkit-ui/react';
```
@@ -212,7 +212,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldSet } from '@databricks/appkit-ui';
+import { FieldSet } from '@databricks/appkit-ui/react';
```
@@ -235,7 +235,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FieldTitle } from '@databricks/appkit-ui';
+import { FieldTitle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/FormControl.mdx b/docs/docs/api/appkit-ui/ui/FormControl.mdx
index 3176b9242..f2c516a54 100644
--- a/docs/docs/api/appkit-ui/ui/FormControl.mdx
+++ b/docs/docs/api/appkit-ui/ui/FormControl.mdx
@@ -20,7 +20,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FormControl } from '@databricks/appkit-ui';
+import { FormControl } from '@databricks/appkit-ui/react';
```
@@ -43,7 +43,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FormDescription } from '@databricks/appkit-ui';
+import { FormDescription } from '@databricks/appkit-ui/react';
```
@@ -75,7 +75,7 @@ Controlled field component for react-hook-form integration
### Usage
```tsx
-import { FormField } from '@databricks/appkit-ui';
+import { FormField } from '@databricks/appkit-ui/react';
```
@@ -98,7 +98,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FormItem } from '@databricks/appkit-ui';
+import { FormItem } from '@databricks/appkit-ui/react';
```
@@ -123,7 +123,7 @@ Label for a form field with error state styling
### Usage
```tsx
-import { FormLabel } from '@databricks/appkit-ui';
+import { FormLabel } from '@databricks/appkit-ui/react';
```
@@ -146,7 +146,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { FormMessage } from '@databricks/appkit-ui';
+import { FormMessage } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/HoverCard.mdx b/docs/docs/api/appkit-ui/ui/HoverCard.mdx
index ee8a37ac9..d4e211711 100644
--- a/docs/docs/api/appkit-ui/ui/HoverCard.mdx
+++ b/docs/docs/api/appkit-ui/ui/HoverCard.mdx
@@ -33,7 +33,7 @@ Content card that appears when hovering over an element
### Usage
```tsx
-import { HoverCard } from '@databricks/appkit-ui';
+import { HoverCard } from '@databricks/appkit-ui/react';
```
@@ -72,7 +72,7 @@ import { HoverCard } from '@databricks/appkit-ui';
### Usage
```tsx
-import { HoverCardContent } from '@databricks/appkit-ui';
+import { HoverCardContent } from '@databricks/appkit-ui/react';
```
@@ -95,7 +95,7 @@ import { HoverCardContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { HoverCardTrigger } from '@databricks/appkit-ui';
+import { HoverCardTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Input.mdx b/docs/docs/api/appkit-ui/ui/Input.mdx
index 41c3a0188..08ef10130 100644
--- a/docs/docs/api/appkit-ui/ui/Input.mdx
+++ b/docs/docs/api/appkit-ui/ui/Input.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Input } from '@databricks/appkit-ui';
+import { Input } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/InputGroup.mdx b/docs/docs/api/appkit-ui/ui/InputGroup.mdx
index c218f2cad..3058f5f98 100644
--- a/docs/docs/api/appkit-ui/ui/InputGroup.mdx
+++ b/docs/docs/api/appkit-ui/ui/InputGroup.mdx
@@ -20,7 +20,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputGroup } from '@databricks/appkit-ui';
+import { InputGroup } from '@databricks/appkit-ui/react';
```
@@ -45,7 +45,7 @@ Decorative content positioned at the start or end of an input group
### Usage
```tsx
-import { InputGroupAddon } from '@databricks/appkit-ui';
+import { InputGroupAddon } from '@databricks/appkit-ui/react';
```
@@ -72,7 +72,7 @@ Button integrated within an input group
### Usage
```tsx
-import { InputGroupButton } from '@databricks/appkit-ui';
+import { InputGroupButton } from '@databricks/appkit-ui/react';
```
@@ -95,7 +95,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputGroupInput } from '@databricks/appkit-ui';
+import { InputGroupInput } from '@databricks/appkit-ui/react';
```
@@ -118,7 +118,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputGroupText } from '@databricks/appkit-ui';
+import { InputGroupText } from '@databricks/appkit-ui/react';
```
@@ -141,7 +141,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputGroupTextarea } from '@databricks/appkit-ui';
+import { InputGroupTextarea } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/InputOTP.mdx b/docs/docs/api/appkit-ui/ui/InputOTP.mdx
index d90ccd899..b403e5c8a 100644
--- a/docs/docs/api/appkit-ui/ui/InputOTP.mdx
+++ b/docs/docs/api/appkit-ui/ui/InputOTP.mdx
@@ -38,7 +38,7 @@ One-time password input with individual character slots
### Usage
```tsx
-import { InputOTP } from '@databricks/appkit-ui';
+import { InputOTP } from '@databricks/appkit-ui/react';
```
@@ -61,7 +61,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputOTPGroup } from '@databricks/appkit-ui';
+import { InputOTPGroup } from '@databricks/appkit-ui/react';
```
@@ -84,7 +84,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { InputOTPSeparator } from '@databricks/appkit-ui';
+import { InputOTPSeparator } from '@databricks/appkit-ui/react';
```
@@ -109,7 +109,7 @@ Individual character slot within the OTP input
### Usage
```tsx
-import { InputOTPSlot } from '@databricks/appkit-ui';
+import { InputOTPSlot } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Item.mdx b/docs/docs/api/appkit-ui/ui/Item.mdx
index 4ed3933ea..3cfdfa310 100644
--- a/docs/docs/api/appkit-ui/ui/Item.mdx
+++ b/docs/docs/api/appkit-ui/ui/Item.mdx
@@ -24,7 +24,7 @@ Flexible container for list items with media, content, and actions
### Usage
```tsx
-import { Item } from '@databricks/appkit-ui';
+import { Item } from '@databricks/appkit-ui/react';
```
@@ -45,7 +45,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemActions } from '@databricks/appkit-ui';
+import { ItemActions } from '@databricks/appkit-ui/react';
```
@@ -66,7 +66,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemContent } from '@databricks/appkit-ui';
+import { ItemContent } from '@databricks/appkit-ui/react';
```
@@ -87,7 +87,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemDescription } from '@databricks/appkit-ui';
+import { ItemDescription } from '@databricks/appkit-ui/react';
```
@@ -108,7 +108,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemFooter } from '@databricks/appkit-ui';
+import { ItemFooter } from '@databricks/appkit-ui/react';
```
@@ -129,7 +129,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemGroup } from '@databricks/appkit-ui';
+import { ItemGroup } from '@databricks/appkit-ui/react';
```
@@ -150,7 +150,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemHeader } from '@databricks/appkit-ui';
+import { ItemHeader } from '@databricks/appkit-ui/react';
```
@@ -173,7 +173,7 @@ import { ItemHeader } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ItemMedia } from '@databricks/appkit-ui';
+import { ItemMedia } from '@databricks/appkit-ui/react';
```
@@ -198,7 +198,7 @@ import { ItemMedia } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ItemSeparator } from '@databricks/appkit-ui';
+import { ItemSeparator } from '@databricks/appkit-ui/react';
```
@@ -219,7 +219,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { ItemTitle } from '@databricks/appkit-ui';
+import { ItemTitle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Kbd.mdx b/docs/docs/api/appkit-ui/ui/Kbd.mdx
index 298863848..342d808bb 100644
--- a/docs/docs/api/appkit-ui/ui/Kbd.mdx
+++ b/docs/docs/api/appkit-ui/ui/Kbd.mdx
@@ -20,7 +20,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Kbd } from '@databricks/appkit-ui';
+import { Kbd } from '@databricks/appkit-ui/react';
```
@@ -41,7 +41,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { KbdGroup } from '@databricks/appkit-ui';
+import { KbdGroup } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Label.mdx b/docs/docs/api/appkit-ui/ui/Label.mdx
index 547a5a16c..21a110b62 100644
--- a/docs/docs/api/appkit-ui/ui/Label.mdx
+++ b/docs/docs/api/appkit-ui/ui/Label.mdx
@@ -29,7 +29,7 @@ Text label associated with form controls
### Usage
```tsx
-import { Label } from '@databricks/appkit-ui';
+import { Label } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Menubar.mdx b/docs/docs/api/appkit-ui/ui/Menubar.mdx
index 5e8ddaf48..efd9c3d11 100644
--- a/docs/docs/api/appkit-ui/ui/Menubar.mdx
+++ b/docs/docs/api/appkit-ui/ui/Menubar.mdx
@@ -34,7 +34,7 @@ Horizontal menu bar with dropdown menus
### Usage
```tsx
-import { Menubar } from '@databricks/appkit-ui';
+import { Menubar } from '@databricks/appkit-ui/react';
```
@@ -62,7 +62,7 @@ import { Menubar } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarCheckboxItem } from '@databricks/appkit-ui';
+import { MenubarCheckboxItem } from '@databricks/appkit-ui/react';
```
@@ -103,7 +103,7 @@ import { MenubarCheckboxItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarContent } from '@databricks/appkit-ui';
+import { MenubarContent } from '@databricks/appkit-ui/react';
```
@@ -126,7 +126,7 @@ import { MenubarContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarGroup } from '@databricks/appkit-ui';
+import { MenubarGroup } from '@databricks/appkit-ui/react';
```
@@ -154,7 +154,7 @@ import { MenubarGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarItem } from '@databricks/appkit-ui';
+import { MenubarItem } from '@databricks/appkit-ui/react';
```
@@ -178,7 +178,7 @@ import { MenubarItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarLabel } from '@databricks/appkit-ui';
+import { MenubarLabel } from '@databricks/appkit-ui/react';
```
@@ -202,7 +202,7 @@ import { MenubarLabel } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarMenu } from '@databricks/appkit-ui';
+import { MenubarMenu } from '@databricks/appkit-ui/react';
```
@@ -226,7 +226,7 @@ import { MenubarMenu } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarPortal } from '@databricks/appkit-ui';
+import { MenubarPortal } from '@databricks/appkit-ui/react';
```
@@ -251,7 +251,7 @@ import { MenubarPortal } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarRadioGroup } from '@databricks/appkit-ui';
+import { MenubarRadioGroup } from '@databricks/appkit-ui/react';
```
@@ -278,7 +278,7 @@ import { MenubarRadioGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarRadioItem } from '@databricks/appkit-ui';
+import { MenubarRadioItem } from '@databricks/appkit-ui/react';
```
@@ -301,7 +301,7 @@ import { MenubarRadioItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarSeparator } from '@databricks/appkit-ui';
+import { MenubarSeparator } from '@databricks/appkit-ui/react';
```
@@ -322,7 +322,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { MenubarShortcut } from '@databricks/appkit-ui';
+import { MenubarShortcut } from '@databricks/appkit-ui/react';
```
@@ -347,7 +347,7 @@ import { MenubarShortcut } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarSub } from '@databricks/appkit-ui';
+import { MenubarSub } from '@databricks/appkit-ui/react';
```
@@ -385,7 +385,7 @@ import { MenubarSub } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarSubContent } from '@databricks/appkit-ui';
+import { MenubarSubContent } from '@databricks/appkit-ui/react';
```
@@ -411,7 +411,7 @@ import { MenubarSubContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarSubTrigger } from '@databricks/appkit-ui';
+import { MenubarSubTrigger } from '@databricks/appkit-ui/react';
```
@@ -434,7 +434,7 @@ import { MenubarSubTrigger } from '@databricks/appkit-ui';
### Usage
```tsx
-import { MenubarTrigger } from '@databricks/appkit-ui';
+import { MenubarTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/NavigationMenu.mdx b/docs/docs/api/appkit-ui/ui/NavigationMenu.mdx
index 008e59c2a..93ea8668d 100644
--- a/docs/docs/api/appkit-ui/ui/NavigationMenu.mdx
+++ b/docs/docs/api/appkit-ui/ui/NavigationMenu.mdx
@@ -37,7 +37,7 @@ Horizontal navigation menu with dropdown submenus
### Usage
```tsx
-import { NavigationMenu } from '@databricks/appkit-ui';
+import { NavigationMenu } from '@databricks/appkit-ui/react';
```
@@ -67,7 +67,7 @@ Dropdown content area for navigation submenu
### Usage
```tsx
-import { NavigationMenuContent } from '@databricks/appkit-ui';
+import { NavigationMenuContent } from '@databricks/appkit-ui/react';
```
@@ -93,7 +93,7 @@ Visual indicator for active navigation menu item
### Usage
```tsx
-import { NavigationMenuIndicator } from '@databricks/appkit-ui';
+import { NavigationMenuIndicator } from '@databricks/appkit-ui/react';
```
@@ -119,7 +119,7 @@ Individual navigation menu item
### Usage
```tsx
-import { NavigationMenuItem } from '@databricks/appkit-ui';
+import { NavigationMenuItem } from '@databricks/appkit-ui/react';
```
@@ -146,7 +146,7 @@ Clickable link within navigation menu
### Usage
```tsx
-import { NavigationMenuLink } from '@databricks/appkit-ui';
+import { NavigationMenuLink } from '@databricks/appkit-ui/react';
```
@@ -171,7 +171,7 @@ Container list for navigation menu items
### Usage
```tsx
-import { NavigationMenuList } from '@databricks/appkit-ui';
+import { NavigationMenuList } from '@databricks/appkit-ui/react';
```
@@ -196,7 +196,7 @@ Button that opens a navigation submenu
### Usage
```tsx
-import { NavigationMenuTrigger } from '@databricks/appkit-ui';
+import { NavigationMenuTrigger } from '@databricks/appkit-ui/react';
```
@@ -222,7 +222,7 @@ Viewport container for navigation menu content
### Usage
```tsx
-import { NavigationMenuViewport } from '@databricks/appkit-ui';
+import { NavigationMenuViewport } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Pagination.mdx b/docs/docs/api/appkit-ui/ui/Pagination.mdx
index 1e930d77f..1ba89cc86 100644
--- a/docs/docs/api/appkit-ui/ui/Pagination.mdx
+++ b/docs/docs/api/appkit-ui/ui/Pagination.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Pagination } from '@databricks/appkit-ui';
+import { Pagination } from '@databricks/appkit-ui/react';
```
@@ -50,7 +50,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { PaginationContent } from '@databricks/appkit-ui';
+import { PaginationContent } from '@databricks/appkit-ui/react';
```
@@ -73,7 +73,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { PaginationEllipsis } from '@databricks/appkit-ui';
+import { PaginationEllipsis } from '@databricks/appkit-ui/react';
```
@@ -96,7 +96,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { PaginationItem } from '@databricks/appkit-ui';
+import { PaginationItem } from '@databricks/appkit-ui/react';
```
@@ -122,7 +122,7 @@ Clickable link for navigating to a specific page
### Usage
```tsx
-import { PaginationLink } from '@databricks/appkit-ui';
+import { PaginationLink } from '@databricks/appkit-ui/react';
```
@@ -148,7 +148,7 @@ Button for navigating to the next page
### Usage
```tsx
-import { PaginationNext } from '@databricks/appkit-ui';
+import { PaginationNext } from '@databricks/appkit-ui/react';
```
@@ -174,7 +174,7 @@ Button for navigating to the previous page
### Usage
```tsx
-import { PaginationPrevious } from '@databricks/appkit-ui';
+import { PaginationPrevious } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Popover.mdx b/docs/docs/api/appkit-ui/ui/Popover.mdx
index 165db05be..4fc1512c4 100644
--- a/docs/docs/api/appkit-ui/ui/Popover.mdx
+++ b/docs/docs/api/appkit-ui/ui/Popover.mdx
@@ -32,7 +32,7 @@ Floating content panel anchored to a trigger element
### Usage
```tsx
-import { Popover } from '@databricks/appkit-ui';
+import { Popover } from '@databricks/appkit-ui/react';
```
@@ -56,7 +56,7 @@ import { Popover } from '@databricks/appkit-ui';
### Usage
```tsx
-import { PopoverAnchor } from '@databricks/appkit-ui';
+import { PopoverAnchor } from '@databricks/appkit-ui/react';
```
@@ -97,7 +97,7 @@ import { PopoverAnchor } from '@databricks/appkit-ui';
### Usage
```tsx
-import { PopoverContent } from '@databricks/appkit-ui';
+import { PopoverContent } from '@databricks/appkit-ui/react';
```
@@ -120,7 +120,7 @@ import { PopoverContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { PopoverTrigger } from '@databricks/appkit-ui';
+import { PopoverTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Progress.mdx b/docs/docs/api/appkit-ui/ui/Progress.mdx
index eaee62c02..7f477e450 100644
--- a/docs/docs/api/appkit-ui/ui/Progress.mdx
+++ b/docs/docs/api/appkit-ui/ui/Progress.mdx
@@ -32,7 +32,7 @@ Visual indicator showing task completion percentage
### Usage
```tsx
-import { Progress } from '@databricks/appkit-ui';
+import { Progress } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/RadioGroup.mdx b/docs/docs/api/appkit-ui/ui/RadioGroup.mdx
index bd82a8405..1b177c514 100644
--- a/docs/docs/api/appkit-ui/ui/RadioGroup.mdx
+++ b/docs/docs/api/appkit-ui/ui/RadioGroup.mdx
@@ -38,7 +38,7 @@ Group of radio buttons for selecting a single option
### Usage
```tsx
-import { RadioGroup } from '@databricks/appkit-ui';
+import { RadioGroup } from '@databricks/appkit-ui/react';
```
@@ -64,7 +64,7 @@ import { RadioGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { RadioGroupItem } from '@databricks/appkit-ui';
+import { RadioGroupItem } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/ResizableHandle.mdx b/docs/docs/api/appkit-ui/ui/ResizableHandle.mdx
index 3595485c2..4902ae40c 100644
--- a/docs/docs/api/appkit-ui/ui/ResizableHandle.mdx
+++ b/docs/docs/api/appkit-ui/ui/ResizableHandle.mdx
@@ -39,7 +39,7 @@ Draggable handle for resizing panels
### Usage
```tsx
-import { ResizableHandle } from '@databricks/appkit-ui';
+import { ResizableHandle } from '@databricks/appkit-ui/react';
```
@@ -74,7 +74,7 @@ Individual resizable panel within a panel group
### Usage
```tsx
-import { ResizablePanel } from '@databricks/appkit-ui';
+import { ResizablePanel } from '@databricks/appkit-ui/react';
```
@@ -105,7 +105,7 @@ Container for resizable panel layout
### Usage
```tsx
-import { ResizablePanelGroup } from '@databricks/appkit-ui';
+import { ResizablePanelGroup } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/ScrollArea.mdx b/docs/docs/api/appkit-ui/ui/ScrollArea.mdx
index 11f808e33..89a6ea46a 100644
--- a/docs/docs/api/appkit-ui/ui/ScrollArea.mdx
+++ b/docs/docs/api/appkit-ui/ui/ScrollArea.mdx
@@ -32,7 +32,7 @@ Container with custom scrollbars for overflow content
### Usage
```tsx
-import { ScrollArea } from '@databricks/appkit-ui';
+import { ScrollArea } from '@databricks/appkit-ui/react';
```
@@ -59,7 +59,7 @@ Scrollbar component for the scroll area
### Usage
```tsx
-import { ScrollBar } from '@databricks/appkit-ui';
+import { ScrollBar } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Select.mdx b/docs/docs/api/appkit-ui/ui/Select.mdx
index e05e8efe2..c6b7640b6 100644
--- a/docs/docs/api/appkit-ui/ui/Select.mdx
+++ b/docs/docs/api/appkit-ui/ui/Select.mdx
@@ -40,7 +40,7 @@ Dropdown control for selecting a value from a list
### Usage
```tsx
-import { Select } from '@databricks/appkit-ui';
+import { Select } from '@databricks/appkit-ui/react';
```
@@ -78,7 +78,7 @@ import { Select } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectContent } from '@databricks/appkit-ui';
+import { SelectContent } from '@databricks/appkit-ui/react';
```
@@ -101,7 +101,7 @@ import { SelectContent } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectGroup } from '@databricks/appkit-ui';
+import { SelectGroup } from '@databricks/appkit-ui/react';
```
@@ -129,7 +129,7 @@ Select item component for individual options in a dropdown.
### Usage
```tsx
-import { SelectItem } from '@databricks/appkit-ui';
+import { SelectItem } from '@databricks/appkit-ui/react';
```
@@ -152,7 +152,7 @@ import { SelectItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectLabel } from '@databricks/appkit-ui';
+import { SelectLabel } from '@databricks/appkit-ui/react';
```
@@ -175,7 +175,7 @@ import { SelectLabel } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectScrollDownButton } from '@databricks/appkit-ui';
+import { SelectScrollDownButton } from '@databricks/appkit-ui/react';
```
@@ -198,7 +198,7 @@ import { SelectScrollDownButton } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectScrollUpButton } from '@databricks/appkit-ui';
+import { SelectScrollUpButton } from '@databricks/appkit-ui/react';
```
@@ -221,7 +221,7 @@ import { SelectScrollUpButton } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectSeparator } from '@databricks/appkit-ui';
+import { SelectSeparator } from '@databricks/appkit-ui/react';
```
@@ -245,7 +245,7 @@ import { SelectSeparator } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectTrigger } from '@databricks/appkit-ui';
+import { SelectTrigger } from '@databricks/appkit-ui/react';
```
@@ -269,7 +269,7 @@ import { SelectTrigger } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SelectValue } from '@databricks/appkit-ui';
+import { SelectValue } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Separator.mdx b/docs/docs/api/appkit-ui/ui/Separator.mdx
index 7cb84afc3..905486d16 100644
--- a/docs/docs/api/appkit-ui/ui/Separator.mdx
+++ b/docs/docs/api/appkit-ui/ui/Separator.mdx
@@ -31,7 +31,7 @@ Visual divider line between content sections
### Usage
```tsx
-import { Separator } from '@databricks/appkit-ui';
+import { Separator } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Sheet.mdx b/docs/docs/api/appkit-ui/ui/Sheet.mdx
index db44e37e9..eda755af5 100644
--- a/docs/docs/api/appkit-ui/ui/Sheet.mdx
+++ b/docs/docs/api/appkit-ui/ui/Sheet.mdx
@@ -32,7 +32,7 @@ Sliding panel that overlays content from screen edges
### Usage
```tsx
-import { Sheet } from '@databricks/appkit-ui';
+import { Sheet } from '@databricks/appkit-ui/react';
```
@@ -57,7 +57,7 @@ Button that closes the sheet
### Usage
```tsx
-import { SheetClose } from '@databricks/appkit-ui';
+import { SheetClose } from '@databricks/appkit-ui/react';
```
@@ -90,7 +90,7 @@ Main content area of the sheet
### Usage
```tsx
-import { SheetContent } from '@databricks/appkit-ui';
+import { SheetContent } from '@databricks/appkit-ui/react';
```
@@ -115,7 +115,7 @@ Description text for the sheet
### Usage
```tsx
-import { SheetDescription } from '@databricks/appkit-ui';
+import { SheetDescription } from '@databricks/appkit-ui/react';
```
@@ -138,7 +138,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SheetFooter } from '@databricks/appkit-ui';
+import { SheetFooter } from '@databricks/appkit-ui/react';
```
@@ -161,7 +161,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SheetHeader } from '@databricks/appkit-ui';
+import { SheetHeader } from '@databricks/appkit-ui/react';
```
@@ -186,7 +186,7 @@ Title text for the sheet
### Usage
```tsx
-import { SheetTitle } from '@databricks/appkit-ui';
+import { SheetTitle } from '@databricks/appkit-ui/react';
```
@@ -211,7 +211,7 @@ Button that opens the sheet
### Usage
```tsx
-import { SheetTrigger } from '@databricks/appkit-ui';
+import { SheetTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Sidebar.mdx b/docs/docs/api/appkit-ui/ui/Sidebar.mdx
index 13368fa4b..5c9fdea3b 100644
--- a/docs/docs/api/appkit-ui/ui/Sidebar.mdx
+++ b/docs/docs/api/appkit-ui/ui/Sidebar.mdx
@@ -31,7 +31,7 @@ Collapsible navigation sidebar with mobile support
### Usage
```tsx
-import { Sidebar } from '@databricks/appkit-ui';
+import { Sidebar } from '@databricks/appkit-ui/react';
```
@@ -54,7 +54,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarContent } from '@databricks/appkit-ui';
+import { SidebarContent } from '@databricks/appkit-ui/react';
```
@@ -77,7 +77,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarFooter } from '@databricks/appkit-ui';
+import { SidebarFooter } from '@databricks/appkit-ui/react';
```
@@ -100,7 +100,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarGroup } from '@databricks/appkit-ui';
+import { SidebarGroup } from '@databricks/appkit-ui/react';
```
@@ -125,7 +125,7 @@ Action button displayed next to a sidebar group label
### Usage
```tsx
-import { SidebarGroupAction } from '@databricks/appkit-ui';
+import { SidebarGroupAction } from '@databricks/appkit-ui/react';
```
@@ -148,7 +148,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarGroupContent } from '@databricks/appkit-ui';
+import { SidebarGroupContent } from '@databricks/appkit-ui/react';
```
@@ -173,7 +173,7 @@ Label heading for a sidebar group
### Usage
```tsx
-import { SidebarGroupLabel } from '@databricks/appkit-ui';
+import { SidebarGroupLabel } from '@databricks/appkit-ui/react';
```
@@ -196,7 +196,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarHeader } from '@databricks/appkit-ui';
+import { SidebarHeader } from '@databricks/appkit-ui/react';
```
@@ -219,7 +219,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarInput } from '@databricks/appkit-ui';
+import { SidebarInput } from '@databricks/appkit-ui/react';
```
@@ -242,7 +242,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarInset } from '@databricks/appkit-ui';
+import { SidebarInset } from '@databricks/appkit-ui/react';
```
@@ -265,7 +265,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarMenu } from '@databricks/appkit-ui';
+import { SidebarMenu } from '@databricks/appkit-ui/react';
```
@@ -291,7 +291,7 @@ Action button displayed alongside a menu item
### Usage
```tsx
-import { SidebarMenuAction } from '@databricks/appkit-ui';
+import { SidebarMenuAction } from '@databricks/appkit-ui/react';
```
@@ -314,7 +314,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarMenuBadge } from '@databricks/appkit-ui';
+import { SidebarMenuBadge } from '@databricks/appkit-ui/react';
```
@@ -341,7 +341,7 @@ import { SidebarMenuBadge } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SidebarMenuButton } from '@databricks/appkit-ui';
+import { SidebarMenuButton } from '@databricks/appkit-ui/react';
```
@@ -364,7 +364,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarMenuItem } from '@databricks/appkit-ui';
+import { SidebarMenuItem } from '@databricks/appkit-ui/react';
```
@@ -389,7 +389,7 @@ Loading skeleton placeholder for menu items
### Usage
```tsx
-import { SidebarMenuSkeleton } from '@databricks/appkit-ui';
+import { SidebarMenuSkeleton } from '@databricks/appkit-ui/react';
```
@@ -412,7 +412,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarMenuSub } from '@databricks/appkit-ui';
+import { SidebarMenuSub } from '@databricks/appkit-ui/react';
```
@@ -439,7 +439,7 @@ Button for submenu items
### Usage
```tsx
-import { SidebarMenuSubButton } from '@databricks/appkit-ui';
+import { SidebarMenuSubButton } from '@databricks/appkit-ui/react';
```
@@ -462,7 +462,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarMenuSubItem } from '@databricks/appkit-ui';
+import { SidebarMenuSubItem } from '@databricks/appkit-ui/react';
```
@@ -487,7 +487,7 @@ import { SidebarMenuSubItem } from '@databricks/appkit-ui';
### Usage
```tsx
-import { SidebarProvider } from '@databricks/appkit-ui';
+import { SidebarProvider } from '@databricks/appkit-ui/react';
```
@@ -510,7 +510,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { SidebarRail } from '@databricks/appkit-ui';
+import { SidebarRail } from '@databricks/appkit-ui/react';
```
@@ -537,7 +537,7 @@ Visual separator between sidebar sections
### Usage
```tsx
-import { SidebarSeparator } from '@databricks/appkit-ui';
+import { SidebarSeparator } from '@databricks/appkit-ui/react';
```
@@ -564,7 +564,7 @@ Button that toggles the sidebar open and closed
### Usage
```tsx
-import { SidebarTrigger } from '@databricks/appkit-ui';
+import { SidebarTrigger } from '@databricks/appkit-ui/react';
```
@@ -587,7 +587,7 @@ This hook takes no parameters.
### Usage
```tsx
-import { useSidebar } from '@databricks/appkit-ui';
+import { useSidebar } from '@databricks/appkit-ui/react';
function MyComponent() {
const sidebar = useSidebar();
diff --git a/docs/docs/api/appkit-ui/ui/Skeleton.mdx b/docs/docs/api/appkit-ui/ui/Skeleton.mdx
index abb766300..27f8abb25 100644
--- a/docs/docs/api/appkit-ui/ui/Skeleton.mdx
+++ b/docs/docs/api/appkit-ui/ui/Skeleton.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Skeleton } from '@databricks/appkit-ui';
+import { Skeleton } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Slider.mdx b/docs/docs/api/appkit-ui/ui/Slider.mdx
index 8402c82f1..392a42e6f 100644
--- a/docs/docs/api/appkit-ui/ui/Slider.mdx
+++ b/docs/docs/api/appkit-ui/ui/Slider.mdx
@@ -43,7 +43,7 @@ Draggable input for selecting numeric values within a range
### Usage
```tsx
-import { Slider } from '@databricks/appkit-ui';
+import { Slider } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Spinner.mdx b/docs/docs/api/appkit-ui/ui/Spinner.mdx
index 007833811..b68f9649f 100644
--- a/docs/docs/api/appkit-ui/ui/Spinner.mdx
+++ b/docs/docs/api/appkit-ui/ui/Spinner.mdx
@@ -20,7 +20,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Spinner } from '@databricks/appkit-ui';
+import { Spinner } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Switch.mdx b/docs/docs/api/appkit-ui/ui/Switch.mdx
index 8fb880781..61c828f5c 100644
--- a/docs/docs/api/appkit-ui/ui/Switch.mdx
+++ b/docs/docs/api/appkit-ui/ui/Switch.mdx
@@ -33,7 +33,7 @@ Toggle control for switching between on and off states
### Usage
```tsx
-import { Switch } from '@databricks/appkit-ui';
+import { Switch } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Table.mdx b/docs/docs/api/appkit-ui/ui/Table.mdx
index 90b5c7d5c..9a3dd9824 100644
--- a/docs/docs/api/appkit-ui/ui/Table.mdx
+++ b/docs/docs/api/appkit-ui/ui/Table.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Table } from '@databricks/appkit-ui';
+import { Table } from '@databricks/appkit-ui/react';
```
@@ -48,7 +48,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableBody } from '@databricks/appkit-ui';
+import { TableBody } from '@databricks/appkit-ui/react';
```
@@ -69,7 +69,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableCaption } from '@databricks/appkit-ui';
+import { TableCaption } from '@databricks/appkit-ui/react';
```
@@ -90,7 +90,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableCell } from '@databricks/appkit-ui';
+import { TableCell } from '@databricks/appkit-ui/react';
```
@@ -111,7 +111,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableFooter } from '@databricks/appkit-ui';
+import { TableFooter } from '@databricks/appkit-ui/react';
```
@@ -132,7 +132,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableHead } from '@databricks/appkit-ui';
+import { TableHead } from '@databricks/appkit-ui/react';
```
@@ -153,7 +153,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableHeader } from '@databricks/appkit-ui';
+import { TableHeader } from '@databricks/appkit-ui/react';
```
@@ -174,7 +174,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { TableRow } from '@databricks/appkit-ui';
+import { TableRow } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Tabs.mdx b/docs/docs/api/appkit-ui/ui/Tabs.mdx
index e6269f43d..e59bc56ba 100644
--- a/docs/docs/api/appkit-ui/ui/Tabs.mdx
+++ b/docs/docs/api/appkit-ui/ui/Tabs.mdx
@@ -35,7 +35,7 @@ Tabbed interface for organizing content into separate panels
### Usage
```tsx
-import { Tabs } from '@databricks/appkit-ui';
+import { Tabs } from '@databricks/appkit-ui/react';
```
@@ -62,7 +62,7 @@ Content panel associated with a tab
### Usage
```tsx
-import { TabsContent } from '@databricks/appkit-ui';
+import { TabsContent } from '@databricks/appkit-ui/react';
```
@@ -88,7 +88,7 @@ Container for tab trigger buttons
### Usage
```tsx
-import { TabsList } from '@databricks/appkit-ui';
+import { TabsList } from '@databricks/appkit-ui/react';
```
@@ -114,7 +114,7 @@ Button that activates a tab panel
### Usage
```tsx
-import { TabsTrigger } from '@databricks/appkit-ui';
+import { TabsTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Textarea.mdx b/docs/docs/api/appkit-ui/ui/Textarea.mdx
index ed7c40c89..42f5cf7af 100644
--- a/docs/docs/api/appkit-ui/ui/Textarea.mdx
+++ b/docs/docs/api/appkit-ui/ui/Textarea.mdx
@@ -27,7 +27,7 @@ This component extends standard HTML element attributes.
### Usage
```tsx
-import { Textarea } from '@databricks/appkit-ui';
+import { Textarea } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Toaster.mdx b/docs/docs/api/appkit-ui/ui/Toaster.mdx
index d3b8dc26c..22cac5d4b 100644
--- a/docs/docs/api/appkit-ui/ui/Toaster.mdx
+++ b/docs/docs/api/appkit-ui/ui/Toaster.mdx
@@ -48,7 +48,7 @@ Toast notification system for displaying temporary messages
### Usage
```tsx
-import { Toaster } from '@databricks/appkit-ui';
+import { Toaster } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Toggle.mdx b/docs/docs/api/appkit-ui/ui/Toggle.mdx
index 45377ae7f..163859fd6 100644
--- a/docs/docs/api/appkit-ui/ui/Toggle.mdx
+++ b/docs/docs/api/appkit-ui/ui/Toggle.mdx
@@ -34,7 +34,7 @@ Button that toggles between pressed and unpressed states
### Usage
```tsx
-import { Toggle } from '@databricks/appkit-ui';
+import { Toggle } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/ToggleGroup.mdx b/docs/docs/api/appkit-ui/ui/ToggleGroup.mdx
index 15a577262..863036750 100644
--- a/docs/docs/api/appkit-ui/ui/ToggleGroup.mdx
+++ b/docs/docs/api/appkit-ui/ui/ToggleGroup.mdx
@@ -41,7 +41,7 @@ Group of toggle buttons for selecting one or more options
### Usage
```tsx
-import { ToggleGroup } from '@databricks/appkit-ui';
+import { ToggleGroup } from '@databricks/appkit-ui/react';
```
@@ -67,7 +67,7 @@ import { ToggleGroup } from '@databricks/appkit-ui';
### Usage
```tsx
-import { ToggleGroupItem } from '@databricks/appkit-ui';
+import { ToggleGroupItem } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/api/appkit-ui/ui/Tooltip.mdx b/docs/docs/api/appkit-ui/ui/Tooltip.mdx
index 7735698c0..50e2dce60 100644
--- a/docs/docs/api/appkit-ui/ui/Tooltip.mdx
+++ b/docs/docs/api/appkit-ui/ui/Tooltip.mdx
@@ -33,7 +33,7 @@ Brief informational message that appears on hover
### Usage
```tsx
-import { Tooltip } from '@databricks/appkit-ui';
+import { Tooltip } from '@databricks/appkit-ui/react';
```
@@ -71,7 +71,7 @@ import { Tooltip } from '@databricks/appkit-ui';
### Usage
```tsx
-import { TooltipContent } from '@databricks/appkit-ui';
+import { TooltipContent } from '@databricks/appkit-ui/react';
```
@@ -98,7 +98,7 @@ Context provider for tooltip configuration
### Usage
```tsx
-import { TooltipProvider } from '@databricks/appkit-ui';
+import { TooltipProvider } from '@databricks/appkit-ui/react';
```
@@ -121,7 +121,7 @@ import { TooltipProvider } from '@databricks/appkit-ui';
### Usage
```tsx
-import { TooltipTrigger } from '@databricks/appkit-ui';
+import { TooltipTrigger } from '@databricks/appkit-ui/react';
```
diff --git a/docs/docs/plugins/analytics.md b/docs/docs/plugins/analytics.md
index 577f6a0c9..b1e208a00 100644
--- a/docs/docs/plugins/analytics.md
+++ b/docs/docs/plugins/analytics.md
@@ -483,7 +483,7 @@ function useLakebaseReadiness() {
```tsx
import { useAnalyticsQuery } from "@databricks/appkit-ui/react";
import { sql } from "@databricks/appkit-ui/js";
-import { Skeleton } from "@databricks/appkit-ui";
+import { Skeleton } from "@databricks/appkit-ui/react";
function SpendTable() {
const { data, loading, error } = useAnalyticsQuery("spend_summary", {
diff --git a/docs/src/components/DocExample/examples.gen.ts b/docs/src/components/DocExample/examples.gen.ts
index 254abe364..2f1330873 100644
--- a/docs/src/components/DocExample/examples.gen.ts
+++ b/docs/src/components/DocExample/examples.gen.ts
@@ -162,25 +162,40 @@ export default function AlertExample() {
},
"area": {
Component: AreaExample,
- source: `"use client";
-
-import { AreaChart } from "@databricks/appkit-ui/react";
+ source: `import { AreaChart } from "@databricks/appkit-ui/react";
+
+// Long rows as \`config/queries/revenue_by_channel.sql\` returns them, one row
+// per month and channel; \`seriesKey\` turns each channel into a stacked band.
+// SELECT DATE_TRUNC('MONTH', order_date) AS month, channel,
+// CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY 1, 2 ORDER BY 1
+const rows = [
+ { month: "2026-01-01", channel: "Online", revenue: 412000 },
+ { month: "2026-01-01", channel: "Retail", revenue: 268000 },
+ { month: "2026-02-01", channel: "Online", revenue: 451000 },
+ { month: "2026-02-01", channel: "Retail", revenue: 259000 },
+ { month: "2026-03-01", channel: "Online", revenue: 498000 },
+ { month: "2026-03-01", channel: "Retail", revenue: 281000 },
+ { month: "2026-04-01", channel: "Online", revenue: 530000 },
+ { month: "2026-04-01", channel: "Retail", revenue: 274000 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
export default function AreaChartExample() {
return (
);
@@ -233,22 +248,35 @@ export default function BadgeExample() {
},
"bar": {
Component: BarExample,
- source: `"use client";
-
-import { BarChart } from "@databricks/appkit-ui/react";
+ source: `import { BarChart } from "@databricks/appkit-ui/react";
+
+// Rows as \`config/queries/revenue_by_segment.sql\` returns them:
+// SELECT segment, CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY segment ORDER BY revenue DESC LIMIT 10
+// In an app, pass the query instead of the rows:
+//
+const rows = [
+ { segment: "Enterprise", revenue: 1840500 },
+ { segment: "Mid-market", revenue: 1215300 },
+ { segment: "SMB", revenue: 864200 },
+ { segment: "Public sector", revenue: 512900 },
+ { segment: "Education", revenue: 301750 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
export default function BarChartExample() {
return (
);
@@ -666,17 +694,37 @@ export default function ContextMenuExample() {
},
"data-table": {
Component: DataTableExample,
- source: `"use client";
-
-import { DataTable } from "@databricks/appkit-ui/react";
+ source: `import { DataTable } from "@databricks/appkit-ui/react";
+
+// Detail rows with typed columns. In an app, pass the query instead of rows:
+//
+const rows = [
+ { order_id: "00412", customer: "Acme", amount: 1840.5, shipped: true },
+ { order_id: "00413", customer: "Globex", amount: 215.0, shipped: false },
+ { order_id: "00414", customer: "Initech", amount: 9310.25, shipped: true },
+ { order_id: "00415", customer: "Hooli", amount: null, shipped: false },
+];
+
+const usd = new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+});
export default function DataTableExample() {
return (
(value == null ? "—" : usd.format(Number(value))),
+ align: "right",
+ },
+ { key: "shipped" },
+ ]}
+ defaultSort={{ key: "amount", desc: true }}
pageSize={10}
/>
);
@@ -744,19 +792,25 @@ export default function DialogExample() {
},
"donut": {
Component: DonutExample,
- source: `"use client";
-
-import { DonutChart } from "@databricks/appkit-ui/react";
+ source: `import { DonutChart } from "@databricks/appkit-ui/react";
+
+// Headcount by department, with the total in the hole.
+// SELECT department, COUNT(*) AS headcount FROM employees
+// GROUP BY department ORDER BY headcount DESC
+const rows = [
+ { department: "Engineering", headcount: 450 },
+ { department: "Sales", headcount: 300 },
+ { department: "Marketing", headcount: 250 },
+ { department: "Operations", headcount: 200 },
+];
export default function DonutChartExample() {
return (
);
@@ -986,31 +1040,31 @@ export default function GenieChatExample() {
},
"heatmap": {
Component: HeatmapExample,
- source: `"use client";
-
-import { HeatmapChart } from "@databricks/appkit-ui/react";
+ source: `import { HeatmapChart } from "@databricks/appkit-ui/react";
+
+// One row per cell, as \`config/queries/orders_by_hour.sql\` returns them.
+// Weekdays are put in calendar order whatever the row order.
+// SELECT DATE_FORMAT(created_at, 'E') AS weekday, HOUR(created_at) AS hour,
+// COUNT(*) AS orders
+// FROM orders GROUP BY 1, 2
+const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
+const hours = [8, 10, 12, 14, 16, 18];
+const rows = weekdays.flatMap((weekday, d) =>
+ hours.map((hour, h) => ({
+ weekday,
+ hour,
+ // Busy at lunch and on weekdays: a fixed pattern, not random data.
+ orders: (d < 5 ? 60 : 25) + (h === 2 ? 40 : 0) + ((d * 7 + h * 3) % 11),
+ })),
+);
export default function HeatmapChartExample() {
- const data = [];
- const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
- const hours = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"];
-
- for (const day of days) {
- for (const hour of hours) {
- data.push({
- day,
- hour,
- count: Math.floor(Math.random() * 100),
- });
- }
- }
-
return (
);
@@ -1117,24 +1171,31 @@ export default function LabelExample() {
},
"line": {
Component: LineExample,
- source: `"use client";
-
-import { LineChart } from "@databricks/appkit-ui/react";
+ source: `import { LineChart } from "@databricks/appkit-ui/react";
+
+// Rows as \`config/queries/daily_orders.sql\` returns them: a DATE column and a
+// count, one row per day. A day with no data is null and shows as a gap with
+// \`defaults="v3"\`.
+// SELECT order_date, COUNT(*) AS orders FROM orders
+// WHERE order_date >= :start_date GROUP BY order_date ORDER BY order_date
+// In an app:
+const rows = [
+ { order_date: "2026-03-01", orders: 182 },
+ { order_date: "2026-03-02", orders: 205 },
+ { order_date: "2026-03-03", orders: 198 },
+ { order_date: "2026-03-04", orders: null },
+ { order_date: "2026-03-05", orders: 231 },
+ { order_date: "2026-03-06", orders: 264 },
+ { order_date: "2026-03-07", orders: 249 },
+];
export default function LineChartExample() {
return (
);
@@ -1441,22 +1502,20 @@ export default function PaginationExample() {
},
"pie": {
Component: PieExample,
- source: `"use client";
-
-import { PieChart } from "@databricks/appkit-ui/react";
+ source: `import { PieChart } from "@databricks/appkit-ui/react";
+
+// Two to five parts of one whole, as \`config/queries/tickets_by_priority.sql\`
+// returns them. More parts, or parts of similar size, read better as a bar chart.
+// SELECT priority, COUNT(*) AS tickets FROM tickets GROUP BY priority ORDER BY tickets DESC
+const rows = [
+ { priority: "Low", tickets: 412 },
+ { priority: "Medium", tickets: 268 },
+ { priority: "High", tickets: 121 },
+ { priority: "Urgent", tickets: 37 },
+];
export default function PieChartExample() {
- return (
-
- );
+ return ;
}
`,
},
@@ -1548,23 +1607,36 @@ export default function ProgressExample() {
},
"radar": {
Component: RadarExample,
- source: `"use client";
+ source: `import { RadarChart } from "@databricks/appkit-ui/react";
-import { RadarChart } from "@databricks/appkit-ui/react";
+// One row per entity, on one 0-100 scale, as a SQL query returns it.
+// \`metrics\` names the spokes; \`max\` fixes the rim at 100.
+// SELECT region, availability, latency_score, error_score, cost_score
+// FROM region_scores
+const rows = [
+ {
+ region: "us-east",
+ availability: 98,
+ latency_score: 82,
+ error_score: 91,
+ cost_score: 64,
+ },
+ {
+ region: "eu-west",
+ availability: 95,
+ latency_score: 88,
+ error_score: 79,
+ cost_score: 72,
+ },
+];
export default function RadarChartExample() {
return (
);
@@ -1637,25 +1709,28 @@ export default function ResizableExample() {
},
"scatter": {
Component: ScatterExample,
- source: `"use client";
-
-import { ScatterChart } from "@databricks/appkit-ui/react";
+ source: `import { ScatterChart } from "@databricks/appkit-ui/react";
+
+// Two measures per entity, as \`config/queries/customer_health.sql\` returns them.
+// Pass both keys: a scatter needs a numeric x and y.
+// SELECT customer, CAST(monthly_spend AS DOUBLE) AS monthly_spend, uptime_pct
+// FROM customer_health
+const rows = [
+ { customer: "Acme", monthly_spend: 5200, uptime_pct: 99.1 },
+ { customer: "Globex", monthly_spend: 5850, uptime_pct: 98.4 },
+ { customer: "Initech", monthly_spend: 5400, uptime_pct: 97.2 },
+ { customer: "Umbrella", monthly_spend: 6000, uptime_pct: 99.5 },
+ { customer: "Hooli", monthly_spend: 5050, uptime_pct: 98.9 },
+ { customer: "Stark", monthly_spend: 5600, uptime_pct: 97.8 },
+];
export default function ScatterChartExample() {
return (
\`\${value}%\`}
height={300}
/>
);
diff --git a/docs/static/appkit-ui/styles.gen.css b/docs/static/appkit-ui/styles.gen.css
index bb120c2ec..610428bc6 100644
--- a/docs/static/appkit-ui/styles.gen.css
+++ b/docs/static/appkit-ui/styles.gen.css
@@ -456,6 +456,9 @@
.mt-auto {
margin-top: auto;
}
+ .-mr-2 {
+ margin-right: calc(var(--spacing) * -2);
+ }
.mr-2 {
margin-right: calc(var(--spacing) * 2);
}
@@ -590,6 +593,10 @@
width: calc(var(--spacing) * 10);
height: calc(var(--spacing) * 10);
}
+ .size-80 {
+ width: calc(var(--spacing) * 80);
+ height: calc(var(--spacing) * 80);
+ }
.size-auto {
width: auto;
height: auto;
@@ -661,12 +668,18 @@
.h-\[1\.15rem\] {
height: 1.15rem;
}
+ .h-\[18rem\] {
+ height: 18rem;
+ }
.h-\[150px\] {
height: 150px;
}
.h-\[200px\] {
height: 200px;
}
+ .h-\[400px\] {
+ height: 400px;
+ }
.h-\[calc\(100\%-1px\)\] {
height: calc(100% - 1px);
}
@@ -700,12 +713,12 @@
.max-h-80 {
max-height: calc(var(--spacing) * 80);
}
+ .max-h-96 {
+ max-height: calc(var(--spacing) * 96);
+ }
.max-h-\[300px\] {
max-height: 300px;
}
- .max-h-\[600px\] {
- max-height: 600px;
- }
.min-h-0 {
min-height: calc(var(--spacing) * 0);
}
@@ -718,6 +731,9 @@
.min-h-\[100vh\] {
min-height: 100vh;
}
+ .min-h-\[200px\] {
+ min-height: 200px;
+ }
.min-h-screen {
min-height: 100vh;
}
@@ -907,6 +923,9 @@
.flex-shrink-0 {
flex-shrink: 0;
}
+ .shrink {
+ flex-shrink: 1;
+ }
.shrink-0 {
flex-shrink: 0;
}
@@ -1760,9 +1779,6 @@
.text-white {
color: var(--color-white);
}
- .capitalize {
- text-transform: capitalize;
- }
.lowercase {
text-transform: lowercase;
}
@@ -4248,6 +4264,11 @@
display: flex;
}
}
+ .md\:h-96 {
+ @media (width >= 48rem) {
+ height: calc(var(--spacing) * 96);
+ }
+ }
.md\:min-h-min {
@media (width >= 48rem) {
min-height: min-content;
diff --git a/packages/appkit-ui/src/js/arrow/arrow-client.test.ts b/packages/appkit-ui/src/js/arrow/arrow-client.test.ts
index d2d83b93a..aa35b93d9 100644
--- a/packages/appkit-ui/src/js/arrow/arrow-client.test.ts
+++ b/packages/appkit-ui/src/js/arrow/arrow-client.test.ts
@@ -1,7 +1,16 @@
-import { Table, tableToIPC, Utf8, vectorFromArray } from "apache-arrow";
+import {
+ DateDay,
+ Decimal,
+ makeVector,
+ Table,
+ TimestampMillisecond,
+ tableToIPC,
+ Utf8,
+ vectorFromArray,
+} from "apache-arrow";
import { describe, expect, test } from "vitest";
-import { ArrowClient } from "./arrow-client";
+import { ArrowClient, arrowRowsToObjects } from "./arrow-client";
/** Build an Arrow IPC stream (2 cols, 2 rows) with the given field names. */
function ipc(names: [string, string]): Uint8Array {
@@ -59,3 +68,38 @@ describe("ArrowClient.processArrowBuffer column relabeling", () => {
]);
});
});
+
+describe("arrowRowsToObjects", () => {
+ test("reads DECIMAL scaled, DATE as a day and TIMESTAMP as an ISO instant", () => {
+ const table = new Table({
+ amount: makeVector({
+ type: new Decimal(2, 10),
+ data: new Uint32Array([123456, 0, 0, 0, 5, 0, 0, 0]),
+ }),
+ day: makeVector({
+ type: new DateDay(),
+ data: new Int32Array([20454, 20455]),
+ }),
+ at: makeVector({
+ type: new TimestampMillisecond(),
+ data: new BigInt64Array([1767225600000n, 1767229200000n]),
+ }),
+ label: vectorFromArray(["a", "b"], new Utf8()),
+ });
+
+ expect(arrowRowsToObjects(table)).toEqual([
+ {
+ amount: 1234.56,
+ day: "2026-01-01",
+ at: "2026-01-01T00:00:00.000Z",
+ label: "a",
+ },
+ {
+ amount: 0.05,
+ day: "2026-01-02",
+ at: "2026-01-01T01:00:00.000Z",
+ label: "b",
+ },
+ ]);
+ });
+});
diff --git a/packages/appkit-ui/src/js/arrow/arrow-client.ts b/packages/appkit-ui/src/js/arrow/arrow-client.ts
index b2a4dc90d..512aa0067 100644
--- a/packages/appkit-ui/src/js/arrow/arrow-client.ts
+++ b/packages/appkit-ui/src/js/arrow/arrow-client.ts
@@ -6,6 +6,7 @@ import {
NAME_FIELD_PATTERNS,
} from "../constants";
import {
+ ARROW_TYPE_IDS,
getArrowModule,
getDecimalTypeId,
getTypeIdSets,
@@ -152,7 +153,30 @@ export class ArrowClient {
*
* @returns xData for axis, yDataMap for series data
*/
- static extractChartData(table: Table, xKey: string, yKeys: string[]) {
+ static extractChartData(
+ table: Table,
+ xKey: string,
+ yKeys: string[],
+ ): {
+ xData: (string | number)[];
+ yDataMap: Record;
+ };
+ /** With `keepNulls`, null cells stay `null` instead of becoming 0. */
+ static extractChartData(
+ table: Table,
+ xKey: string,
+ yKeys: string[],
+ opts: { keepNulls: boolean },
+ ): {
+ xData: (string | number | null)[];
+ yDataMap: Record;
+ };
+ static extractChartData(
+ table: Table,
+ xKey: string,
+ yKeys: string[],
+ opts: { keepNulls: boolean } = { keepNulls: false },
+ ) {
// Early exit for empty tables - return cached empty object
if (table.numRows === 0) {
return EMPTY_RESULT;
@@ -175,14 +199,22 @@ export class ArrowClient {
// Extract X column using proper value extraction
const xCol = table.getChild(xKey);
- const xData = extractColumnValues(xCol, decimalDivisors.get(xKey));
+ const xData = extractColumnValues(
+ xCol,
+ decimalDivisors.get(xKey),
+ opts.keepNulls,
+ );
// Extract Y columns using proper value extraction
- const yDataMap: Record = {};
+ const yDataMap: Record = {};
for (let i = 0; i < yKeys.length; i++) {
const key = yKeys[i];
const col = table.getChild(key);
- yDataMap[key] = extractColumnValues(col, decimalDivisors.get(key));
+ yDataMap[key] = extractColumnValues(
+ col,
+ decimalDivisors.get(key),
+ opts.keepNulls,
+ );
}
return { xData, yDataMap };
@@ -375,6 +407,55 @@ const EMPTY_RESULT: {
yDataMap: {},
};
+/**
+ * Arrow rows in the shape the JSON rows have: DECIMAL scaled to its value, DATE
+ * as `YYYY-MM-DD` (the UTC day Arrow stores) and TIMESTAMP as an ISO 8601
+ * instant. `row.toJSON()` keeps DECIMAL as its unscaled integer and DATE and
+ * TIMESTAMP as epoch milliseconds, so transformers and tables read them wrong.
+ *
+ * Note: assumes Arrow has been loaded (via processArrowBuffer or a Table).
+ */
+export function arrowRowsToObjects(table: Table): Record[] {
+ const decimalType = getDecimalTypeId();
+ const scaled = table.schema.fields.flatMap((field) => {
+ const decType = field.type as { scale?: number };
+ const isDecimal = field.typeId === decimalType;
+ const isDate = field.typeId === ARROW_TYPE_IDS.Date;
+ const isTimestamp = field.typeId === ARROW_TYPE_IDS.Timestamp;
+ if (!isDecimal && !isDate && !isTimestamp) return [];
+ const divisor =
+ isDecimal && typeof decType.scale === "number"
+ ? 10 ** decType.scale
+ : undefined;
+ return [
+ {
+ name: field.name,
+ column: table.getChild(field.name),
+ divisor,
+ isDate,
+ isTimestamp,
+ },
+ ];
+ });
+ if (!scaled.length) return Array.from(table, (row) => ({ ...row.toJSON() }));
+
+ return Array.from(table, (row, i) => {
+ const json: Record = { ...row.toJSON() };
+ for (const { name, column, divisor, isDate, isTimestamp } of scaled) {
+ const value = column?.get(i);
+ if (value === null || value === undefined) {
+ json[name] = null;
+ } else if (divisor !== undefined) {
+ json[name] = Number(value) / divisor;
+ } else if (typeof value === "number" && Number.isFinite(value)) {
+ const iso = new Date(value).toISOString();
+ json[name] = isDate ? iso.slice(0, 10) : isTimestamp ? iso : value;
+ }
+ }
+ return json;
+ });
+}
+
/**
* Extracts values from an Arrow Vector properly.
* Uses get(i) to handle complex types like Decimal128 correctly.
@@ -386,17 +467,18 @@ const EMPTY_RESULT: {
function extractColumnValues(
col: { length: number; get: (i: number) => unknown } | null | undefined,
divisor?: number,
-): (string | number)[] {
+ keepNulls = false,
+): (string | number | null)[] {
if (!col) return [];
// Pre-allocate array for better performance with large datasets
const len = col.length;
- const result: (string | number)[] = new Array(len);
+ const result: (string | number | null)[] = new Array(len);
for (let i = 0; i < len; i++) {
const val = col.get(i);
if (val === null || val === undefined) {
- result[i] = 0;
+ result[i] = keepNulls ? null : 0;
} else if (typeof val === "bigint") {
// Apply decimal scaling if needed
const num = Number(val);
diff --git a/packages/appkit-ui/src/js/arrow/lazy-arrow.ts b/packages/appkit-ui/src/js/arrow/lazy-arrow.ts
index c36a7fa4a..517e9674e 100644
--- a/packages/appkit-ui/src/js/arrow/lazy-arrow.ts
+++ b/packages/appkit-ui/src/js/arrow/lazy-arrow.ts
@@ -41,15 +41,77 @@ let numericTypeIds: Set | null = null;
let stringTypeIds: Set | null = null;
let decimalTypeId: number | null = null;
+type ArrowTypeEnum = typeof import("apache-arrow").Type;
+type TypeIdKey =
+ | "Date"
+ | "DateDay"
+ | "DateMillisecond"
+ | "Timestamp"
+ | "TimestampSecond"
+ | "TimestampMillisecond"
+ | "TimestampMicrosecond"
+ | "TimestampNanosecond"
+ | "Time"
+ | "TimeSecond"
+ | "TimeMillisecond"
+ | "TimeMicrosecond"
+ | "TimeNanosecond"
+ | "Int"
+ | "Int8"
+ | "Int16"
+ | "Int32"
+ | "Int64"
+ | "Uint8"
+ | "Uint16"
+ | "Uint32"
+ | "Uint64"
+ | "Float"
+ | "Float16"
+ | "Float32"
+ | "Float64"
+ | "Decimal"
+ | "Utf8"
+ | "LargeUtf8";
+
/**
- * Initializes the type ID sets from the Arrow Type enum.
- * Call this after loading the Arrow module.
+ * The Arrow `Type` ids used for field detection. They are part of the Arrow
+ * format, so they are fixed; a test checks them against `apache-arrow`. This
+ * lets detection run on a Table the app built itself, before (or without)
+ * this package ever loading Arrow.
*/
-export async function initializeTypeIdSets(): Promise {
- if (temporalTypeIds !== null) return; // Already initialized
-
- const { Type } = await getArrowModule();
+export const ARROW_TYPE_IDS: Readonly> = {
+ Date: 8,
+ DateDay: -13,
+ DateMillisecond: -14,
+ Timestamp: 10,
+ TimestampSecond: -15,
+ TimestampMillisecond: -16,
+ TimestampMicrosecond: -17,
+ TimestampNanosecond: -18,
+ Time: 9,
+ TimeSecond: -19,
+ TimeMillisecond: -20,
+ TimeMicrosecond: -21,
+ TimeNanosecond: -22,
+ Int: 2,
+ Int8: -2,
+ Int16: -3,
+ Int32: -4,
+ Int64: -5,
+ Uint8: -6,
+ Uint16: -7,
+ Uint32: -8,
+ Uint64: -9,
+ Float: 3,
+ Float16: -10,
+ Float32: -11,
+ Float64: -12,
+ Decimal: 7,
+ Utf8: 5,
+ LargeUtf8: 20,
+};
+function setTypeIdSets(Type: Readonly>): void {
temporalTypeIds = new Set([
Type.Date,
Type.DateDay,
@@ -88,20 +150,38 @@ export async function initializeTypeIdSets(): Promise {
decimalTypeId = Type.Decimal;
}
+/**
+ * Initializes the type ID sets from the Arrow Type enum.
+ * Call this after loading the Arrow module.
+ */
+export async function initializeTypeIdSets(): Promise {
+ if (temporalTypeIds !== null) return; // Already initialized
+
+ const { Type } = await getArrowModule();
+ setTypeIdSets(Type satisfies ArrowTypeEnum);
+}
+
+/**
+ * Initializes the type ID sets synchronously from {@link ARROW_TYPE_IDS} when
+ * they are not set yet. An Arrow Table passed as chart `data` never went
+ * through `processArrowBuffer`, so detection must not depend on it.
+ */
+function ensureTypeIdSets(): void {
+ if (temporalTypeIds === null) setTypeIdSets(ARROW_TYPE_IDS);
+}
+
/**
* Returns the cached type ID sets.
- * Throws if called before initializeTypeIdSets().
- * This is safe because you can't have a Table without first loading Arrow.
+ * Initializes them from the fixed Arrow type ids on first use.
*/
export function getTypeIdSets(): {
temporal: Set;
numeric: Set;
string: Set;
} {
+ ensureTypeIdSets();
if (!temporalTypeIds || !numericTypeIds || !stringTypeIds) {
- throw new Error(
- "Arrow type IDs not initialized. Call initializeTypeIdSets() first.",
- );
+ throw new Error("Arrow type IDs could not be initialized.");
}
return {
temporal: temporalTypeIds,
@@ -111,14 +191,12 @@ export function getTypeIdSets(): {
}
/**
- * Returns the Decimal type ID.
- * Throws if called before initializeTypeIdSets().
+ * Returns the Decimal type ID, initializing the type ids on first use.
*/
export function getDecimalTypeId(): number {
+ ensureTypeIdSets();
if (decimalTypeId === null) {
- throw new Error(
- "Arrow type IDs not initialized. Call initializeTypeIdSets() first.",
- );
+ throw new Error("Arrow type IDs could not be initialized.");
}
return decimalTypeId;
}
diff --git a/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts b/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts
new file mode 100644
index 000000000..060b66871
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts
@@ -0,0 +1,134 @@
+import {
+ DateDay,
+ Float64,
+ makeVector,
+ Table,
+ Type,
+ tableFromArrays,
+ vectorFromArray,
+} from "apache-arrow";
+import { describe, expect, test } from "vitest";
+
+import { ARROW_TYPE_IDS } from "@/js/arrow/lazy-arrow";
+
+import {
+ NULL_X_LABEL,
+ normalizeChartData,
+ normalizeHeatmapData,
+} from "../normalize";
+
+// This file never calls ArrowClient.processArrowBuffer, like an app that
+// builds its own Table and passes it as `data`.
+describe("Arrow Table as data", () => {
+ test("category rows normalize without prior Arrow initialization", () => {
+ const table = tableFromArrays({
+ region: ["east", "west"],
+ revenue: Float64Array.from([1, 2]),
+ });
+ const n = normalizeChartData(table, "region", "revenue");
+ expect(n.chartType).toBe("categorical");
+ expect(n.xData).toEqual(["east", "west"]);
+ expect(n.yDataMap.revenue).toEqual([1, 2]);
+ });
+
+ test("auto-detection works on an Arrow Table", () => {
+ const table = tableFromArrays({
+ region: ["east", "west"],
+ revenue: Float64Array.from([1, 2]),
+ });
+ const n = normalizeChartData(table);
+ expect(n.xField).toBe("region");
+ expect(n.yFields).toEqual(["revenue"]);
+ });
+
+ test("heatmap still works", () => {
+ const table = tableFromArrays({
+ x: ["a", "b"],
+ y: ["r", "r"],
+ v: Float64Array.from([1, 2]),
+ });
+ expect(normalizeHeatmapData(table, "x", "y", "v").heatmapData).toHaveLength(
+ 2,
+ );
+ });
+
+ test("the fixed type ids match apache-arrow", () => {
+ for (const [name, id] of Object.entries(ARROW_TYPE_IDS)) {
+ expect(Type[name as keyof typeof Type], name).toBe(id);
+ }
+ });
+});
+
+describe("one detection path for Arrow and JSON", () => {
+ const cases: Record[] = [
+ { region: ["east", "west"], revenue: [1, 2] },
+ { period: ["Q1", "Q2"], revenue: [1, 2] },
+ { day: ["2026-01-01", "2026-01-02"], revenue: [1, 2] },
+ {
+ created_at: ["2026-01-01", "2026-01-02"],
+ day: ["2026-02-01", "2026-02-02"],
+ revenue: [1, 2],
+ },
+ { user_id: ["a", "b"], label: ["x", "y"], revenue: [1, 2] },
+ ];
+
+ test.each(cases.map((c) => [Object.keys(c).join(","), c]))(
+ "%s detects the same fields",
+ (_name, columns) => {
+ const cols = columns as Record;
+ const table = tableFromArrays(
+ Object.fromEntries(
+ Object.entries(cols).map(([k, v]) => [
+ k,
+ typeof v[0] === "number" ? Float64Array.from(v as number[]) : v,
+ ]),
+ ) as Parameters[0],
+ );
+ const rows = cols[Object.keys(cols)[0]].map((_, i) =>
+ Object.fromEntries(Object.entries(cols).map(([k, v]) => [k, v[i]])),
+ );
+ const fromArrow = normalizeChartData(table);
+ const fromJson = normalizeChartData(rows);
+ expect(fromArrow.xField).toBe(fromJson.xField);
+ expect(fromArrow.yFields).toEqual(fromJson.yFields);
+ expect(fromArrow.chartType).toBe(fromJson.chartType);
+ },
+ );
+
+ test("a text column named period is not a date in Arrow either", () => {
+ const table = tableFromArrays({
+ period: ["Q1", "Q2"],
+ revenue: Float64Array.from([1, 2]),
+ });
+ expect(normalizeChartData(table).chartType).toBe("categorical");
+ });
+});
+
+describe("Arrow x columns: DATE days and null labels", () => {
+ test("a DATE x column is a date-only time axis at local midnight", () => {
+ const table = new Table({
+ day: makeVector({
+ type: new DateDay(),
+ data: new Int32Array([20454, 20455]),
+ }),
+ revenue: vectorFromArray([1, 2], new Float64()),
+ });
+ const n = normalizeChartData(table, "day", "revenue");
+ expect(n.chartType).toBe("timeseries");
+ expect(n.xDateOnly).toBe(true);
+ expect(n.xData).toEqual([
+ new Date(2026, 0, 1).getTime(),
+ new Date(2026, 0, 2).getTime(),
+ ]);
+ });
+
+ test("a null x is labelled (null), not 0", () => {
+ const table = tableFromArrays({
+ region: ["east", null],
+ revenue: Float64Array.from([1, 2]),
+ });
+ const n = normalizeChartData(table, "region", "revenue");
+ expect(n.xData).toContain(NULL_X_LABEL);
+ expect(n.xData).not.toContain(0);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx
new file mode 100644
index 000000000..c0aeaa3cf
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx
@@ -0,0 +1,76 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test } from "vitest";
+
+import { BaseChart } from "../base";
+import type { ChartDefaults } from "../types";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(installEChartsEnv);
+afterEach(cleanup);
+
+type AxisOption = { yAxis: { type: string }[] };
+
+async function isHorizontal(
+ data: Record[],
+ xKey: string,
+ defaults?: ChartDefaults,
+): Promise {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const horizontal =
+ chartOption(container)?.yAxis[0].type === "category";
+ cleanup();
+ return horizontal;
+}
+
+const segments = ["Retail", "Online", "Partner"].map((segment, i) => ({
+ segment,
+ v: i + 1,
+}));
+const years = [2021, 2022, 2023].map((year, i) => ({ year, v: i + 1 }));
+const manyLabels = Array.from({ length: 9 }, (_, i) => ({
+ segment: `S${i}`,
+ v: i,
+}));
+const longLabels = [
+ { segment: "Consumer Electronics", v: 1 },
+ { segment: "Home", v: 2 },
+];
+const days = [
+ { day: "2026-01-01", v: 1 },
+ { day: "2026-01-02", v: 2 },
+];
+
+describe("bar orientation without the prop", () => {
+ test("today's rule: category labels horizontal, dates vertical", async () => {
+ expect(await isHorizontal(segments, "segment")).toBe(true);
+ expect(await isHorizontal(days, "day")).toBe(false);
+ });
+
+ test("v3: up to 7 short labels are vertical", async () => {
+ expect(await isHorizontal(segments, "segment", "v3")).toBe(false);
+ });
+
+ test("v3: more than 7 labels or long labels are horizontal", async () => {
+ expect(await isHorizontal(manyLabels, "segment", "v3")).toBe(true);
+ expect(await isHorizontal(longLabels, "segment", "v3")).toBe(true);
+ });
+
+ test("v3: dates stay vertical", async () => {
+ expect(await isHorizontal(days, "day", "v3")).toBe(false);
+ });
+});
+
+describe("numeric x such as years", () => {
+ test("v3: years render vertical", async () => {
+ expect(await isHorizontal(years, "year", "v3")).toBe(false);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx
index 49daa4668..46a9d8241 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx
+++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx
@@ -109,6 +109,12 @@ const cartesianData = [
{ month: "Mar", revenue: 90, cost: 50 },
];
+const scatterData = [
+ { spend: 10, revenue: 100, cost: 60 },
+ { spend: 20, revenue: 120, cost: 70 },
+ { spend: 30, revenue: 90, cost: 50 },
+];
+
const heatmapData = [
{ day: "Mon", hour: "9am", value: 3 },
{ day: "Mon", hour: "10am", value: 7 },
@@ -122,11 +128,13 @@ describe("BaseChart ECharts registration", () => {
test.each(cartesianTypes)(
"renders %s chart without missing-registration errors",
async (chartType) => {
+ // A scatter needs a numeric x; the others plot months.
+ const isScatter = chartType === "scatter";
const { container } = render(
,
@@ -331,3 +339,408 @@ describe("BaseChart sizing", () => {
expect(root.style.minHeight).toBe("");
});
});
+
+describe("unknown keys", () => {
+ test("a yKey that is not in the rows shows an error with the available keys", () => {
+ const errors: string[] = [];
+ vi.mocked(console.error).mockImplementation((...args: unknown[]) => {
+ errors.push(args.map(String).join(" "));
+ });
+ const { getByRole, container } = render(
+ ,
+ );
+ const alert = getByRole("alert");
+ expect(alert.textContent).toContain('yKey "revnue"');
+ expect(alert.textContent).toContain("Available keys: month, revenue, cost");
+ expect(container.querySelector("canvas")).toBeNull();
+ expect(errors.some((e) => e.includes('yKey "revnue"'))).toBe(true);
+ });
+
+ test("an unknown xKey is reported too", () => {
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain('xKey "mnth"');
+ });
+});
+
+describe("date-only time axis", () => {
+ test("renders a DATE time axis without uncaught errors", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ });
+});
+
+describe("repeated x values", () => {
+ const longRows = [
+ { day: "Mon", region: "east", revenue: 1 },
+ { day: "Mon", region: "west", revenue: 2 },
+ { day: "Tue", region: "east", revenue: 3 },
+ ];
+
+ test("warns and points at seriesKey", () => {
+ render(
+ ,
+ );
+ expect(
+ vi
+ .mocked(console.warn)
+ .mock.calls.some((c) => String(c[0]).includes("pass seriesKey")),
+ ).toBe(true);
+ });
+
+ test("no warning with seriesKey", () => {
+ render(
+ ,
+ );
+ expect(
+ vi
+ .mocked(console.warn)
+ .mock.calls.some((c) => String(c[0]).includes("pass seriesKey")),
+ ).toBe(false);
+ });
+});
+
+describe("radar options", () => {
+ test("a partial radar option keeps the metric list and renders", async () => {
+ const pageErrors: unknown[] = [];
+ const onError = (e: ErrorEvent) => pageErrors.push(e.error);
+ window.addEventListener("error", onError);
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ window.removeEventListener("error", onError);
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ radar: { indicator: { name: string }[]; splitNumber: number }[];
+ };
+ expect(option.radar[0].indicator.map((i) => i.name)).toEqual([
+ "Speed",
+ "Power",
+ "Range",
+ ]);
+ expect(option.radar[0].splitNumber).toBe(4);
+ expect(pageErrors).toEqual([]);
+ });
+});
+
+describe("updates after mount", () => {
+ test("series removed from yKey leave the chart", async () => {
+ const { container, rerender } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ rerender(
+ ,
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ await waitFor(() => {
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ series: unknown[];
+ legend?: unknown[];
+ };
+ expect(option.series).toHaveLength(1);
+ expect(option.legend ?? []).toHaveLength(0);
+ });
+ });
+});
+
+describe("rebuilding the option keeps the reader's zoom and legend", () => {
+ test("a zoomed range survives an option rebuild", async () => {
+ const { container, rerender } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const chart = echarts.getInstanceByDom(root);
+ chart?.dispatchAction({ type: "dataZoom", start: 20, end: 60 });
+ rerender(
+ ,
+ );
+ await waitFor(() => {
+ const option = chart?.getOption() as {
+ title: { text: string }[];
+ dataZoom: { start: number; end: number }[];
+ };
+ expect(option.title[0].text).toBe("second");
+ expect(option.dataZoom[0]).toMatchObject({ start: 20, end: 60 });
+ });
+ });
+
+ test("a legend entry the reader hid stays hidden after a rebuild", async () => {
+ const { container, rerender } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const chart = echarts.getInstanceByDom(root);
+ chart?.dispatchAction({ type: "legendToggleSelect", name: "Cost" });
+ rerender(
+ ,
+ );
+ await waitFor(() => {
+ const option = chart?.getOption() as {
+ title: { text: string }[];
+ legend: { selected: Record }[];
+ };
+ expect(option.title[0].text).toBe("second");
+ expect(option.legend[0].selected.Cost).toBe(false);
+ expect(option.legend[0].selected.Revenue).toBe(true);
+ });
+ });
+});
+
+describe("orientation on line and area", () => {
+ test.each(["line", "area"] as const)(
+ "%s ignores orientation and keeps line series",
+ async (chartType) => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector(
+ "[_echarts_instance_]",
+ ) as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ series: { type: string }[];
+ xAxis: { type: string }[];
+ };
+ expect(option.series[0].type).toBe("line");
+ expect(option.xAxis[0].type).toBe("category");
+ },
+ );
+});
+
+describe("scatter with text x", () => {
+ test("shows an error instead of an empty plot", () => {
+ const errors: string[] = [];
+ vi.mocked(console.error).mockImplementation((...args: unknown[]) => {
+ errors.push(args.map(String).join(" "));
+ });
+ const { getByRole, container } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain(
+ 'xKey "customer" holds text',
+ );
+ expect(container.querySelector("canvas")).toBeNull();
+ expect(errors.some((e) => e.includes("holds text"))).toBe(true);
+ });
+
+ test("numeric x still renders", async () => {
+ const { container, queryByRole } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ expect(queryByRole("alert")).toBeNull();
+ });
+});
+
+describe("scatter over dates", () => {
+ test("plots DATE strings on a time axis", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ xAxis: { type: string }[];
+ series: { data: [number, number][] }[];
+ };
+ expect(option.xAxis[0].type).toBe("time");
+ expect(option.series[0].data[0][0]).toBe(new Date(2026, 0, 1).getTime());
+ });
+});
+
+describe("reference lines", () => {
+ test.each([
+ ["line", undefined],
+ ["bar", "horizontal"],
+ ] as const)(
+ "%s %s draws a labelled markLine",
+ async (chartType, orientation) => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector(
+ "[_echarts_instance_]",
+ ) as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ series: { markLine?: { data: Record[] } }[];
+ };
+ const line = option.series[0].markLine?.data[0];
+ expect(line?.[orientation ? "xAxis" : "yAxis"]).toBe(100);
+ expect((line?.label as { formatter: string }).formatter).toBe("Target");
+ expect(registrationErrors).toEqual([]);
+ },
+ );
+});
+
+describe("zoom", () => {
+ test("adds inside and slider zoom along x without registration errors", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ dataZoom: { type: string; xAxisIndex: number[] }[];
+ };
+ expect(option.dataZoom.map((z) => z.type).sort()).toEqual([
+ "inside",
+ "slider",
+ ]);
+ expect(registrationErrors).toEqual([]);
+ });
+
+ test("no zoom by default", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() =>
+ expect(container.querySelector("canvas")).not.toBeNull(),
+ );
+ const root = container.querySelector("[_echarts_instance_]") as HTMLElement;
+ const option = echarts.getInstanceByDom(root)?.getOption() as {
+ dataZoom?: unknown[];
+ };
+ expect(option.dataZoom ?? []).toHaveLength(0);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts
new file mode 100644
index 000000000..362d7f60e
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts
@@ -0,0 +1,1281 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ applySelectionEmphasis,
+ buildCartesianOption,
+ buildHorizontalBarOption,
+ type CartesianContext,
+ mergeChartOptions,
+} from "../options";
+
+type Series = Record;
+type Option = { series: Series[]; [key: string]: unknown };
+
+function cartesian(overrides: Partial = {}): Option {
+ return buildCartesianOption({
+ xData: ["A", "B", "C"],
+ yDataMap: { a: [1, 2, 3], b: [4, 5, 6] },
+ yFields: ["a", "b"],
+ colors: ["#ff0000", "#00ff00"],
+ showLegend: true,
+ chartType: "bar",
+ isTimeSeries: false,
+ stacked: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 8,
+ ...overrides,
+ }) as Option;
+}
+
+describe("vertical stacked bars", () => {
+ test("stacked applies a stack to vertical bar series", () => {
+ const option = cartesian({ stacked: true });
+ expect(option.series.map((s) => s.stack)).toEqual(["total", "total"]);
+ });
+
+ test("unstacked bars have no stack", () => {
+ const option = cartesian();
+ expect(option.series.map((s) => s.stack)).toEqual([undefined, undefined]);
+ });
+});
+
+describe("horizontal bar row order", () => {
+ const ctx = {
+ xData: ["Big", "Mid", "Small"],
+ yDataMap: { v: [30, 20, 10] },
+ yFields: ["v"],
+ colors: ["#ff0000"],
+ showLegend: false,
+ };
+
+ test("v3 puts the first row on top", () => {
+ const option = buildHorizontalBarOption({ ...ctx, v3: true }, false) as {
+ yAxis: { inverse?: boolean };
+ };
+ expect(option.yAxis.inverse).toBe(true);
+ });
+
+ test("without v3 the axis is unchanged", () => {
+ const option = buildHorizontalBarOption(ctx, false) as {
+ yAxis: { inverse?: boolean };
+ };
+ expect(option.yAxis.inverse).toBeUndefined();
+ });
+});
+
+describe("category labels sized by width", () => {
+ const labels = Array.from(
+ { length: 12 },
+ (_, i) => `Consumer Electronics ${i}`,
+ );
+ const yDataMap = { a: labels.map((_, i) => i) };
+
+ test("with a measured width every label is drawn and truncated to its slot", () => {
+ const option = cartesian({
+ xData: labels.slice(0, 5),
+ yDataMap: { a: [1, 2, 3, 4, 5] },
+ yFields: ["a"],
+ chartWidth: 800,
+ }) as unknown as { xAxis: { axisLabel: Record } };
+ expect(option.xAxis.axisLabel).toMatchObject({
+ interval: 0,
+ width: 120,
+ overflow: "truncate",
+ });
+ expect(option.xAxis.axisLabel.formatter).toBeUndefined();
+ });
+
+ test("narrow slots rotate the labels", () => {
+ const option = cartesian({
+ xData: labels,
+ yDataMap,
+ yFields: ["a"],
+ chartWidth: 400,
+ }) as unknown as { xAxis: { axisLabel: Record } };
+ expect(option.xAxis.axisLabel).toMatchObject({
+ rotate: 45,
+ overflow: "truncate",
+ });
+ });
+
+ test("horizontal bar labels get a share of the width", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: labels,
+ yDataMap,
+ yFields: ["a"],
+ colors: ["#ff0000"],
+ showLegend: false,
+ chartWidth: 600,
+ },
+ false,
+ ) as { yAxis: { axisLabel: Record } };
+ expect(option.yAxis.axisLabel).toMatchObject({
+ width: 180,
+ overflow: "truncate",
+ });
+ expect(option.yAxis.axisLabel.formatter).toBeUndefined();
+ });
+
+ test("without a width labels keep the character cut", () => {
+ const option = cartesian({
+ xData: labels.slice(0, 2),
+ yDataMap: { a: [1, 2] },
+ yFields: ["a"],
+ }) as unknown as {
+ xAxis: { axisLabel: { formatter: (v: string) => string } };
+ };
+ expect(option.xAxis.axisLabel.formatter("Consumer Electronics")).toBe(
+ "Consumer E...",
+ );
+ });
+});
+
+describe("axis names", () => {
+ type Axes = {
+ xAxis: Record;
+ yAxis: Record;
+ };
+
+ test("today: names at the axis end", () => {
+ const option = cartesian({ yFields: ["a"] }) as unknown as Axes;
+ expect(option.xAxis.name).toBeUndefined();
+ const withField = cartesian({
+ yFields: ["a"],
+ xField: "segment",
+ }) as unknown as Axes;
+ expect(withField.xAxis.name).toBe("Segment");
+ expect(withField.yAxis.name).toBe("A");
+ });
+
+ test("v3: no axis names on bar, line and area", () => {
+ const option = cartesian({
+ yFields: ["a"],
+ xField: "segment",
+ v3: true,
+ }) as unknown as Axes;
+ expect(option.xAxis).not.toHaveProperty("name");
+ expect(option.yAxis).not.toHaveProperty("name");
+ });
+
+ test("v3: scatter keeps centred axis names", () => {
+ const option = cartesian({
+ chartType: "scatter",
+ xData: [1, 2],
+ yDataMap: { a: [3, 4] },
+ yFields: ["a"],
+ xField: "spend",
+ v3: true,
+ }) as unknown as Axes;
+ expect(option.xAxis).toMatchObject({
+ name: "Spend",
+ nameLocation: "middle",
+ });
+ expect(option.yAxis).toMatchObject({ name: "A", nameLocation: "middle" });
+ });
+});
+
+describe("horizontal bar grid", () => {
+ test("reserves label space with pixel margins", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { a: [1, 2] },
+ yFields: ["a"],
+ colors: ["#ff0000"],
+ showLegend: true,
+ },
+ false,
+ ) as { grid: Record };
+ expect(option.grid).toEqual({
+ left: 8,
+ right: 24,
+ top: 12,
+ bottom: 8,
+ containLabel: true,
+ });
+ });
+});
+
+describe("bars over dates", () => {
+ const days = [
+ Date.UTC(2026, 0, 1),
+ Date.UTC(2026, 0, 2),
+ Date.UTC(2026, 0, 3),
+ ].map((t) => new Date(t).setHours(0, 0, 0, 0));
+
+ test("use a category axis of formatted dates with one label per bar", () => {
+ const option = cartesian({
+ xData: days,
+ yDataMap: { a: [1, 2, 3] },
+ yFields: ["a"],
+ isTimeSeries: true,
+ xDateOnly: true,
+ }) as unknown as {
+ xAxis: {
+ type: string;
+ data: number[];
+ axisLabel: { formatter: (v: number) => string };
+ };
+ series: { data: unknown[] }[];
+ };
+ expect(option.xAxis.type).toBe("category");
+ expect(option.xAxis.data).toEqual(days);
+ expect(option.xAxis.axisLabel.formatter(days[0])).toBe("2026-01-01");
+ expect(option.series[0].data).toEqual([1, 2, 3]);
+ });
+
+ test("lines over dates keep the time axis", () => {
+ const option = cartesian({
+ chartType: "line",
+ xData: days,
+ yDataMap: { a: [1, 2, 3] },
+ yFields: ["a"],
+ isTimeSeries: true,
+ }) as unknown as { xAxis: { type: string } };
+ expect(option.xAxis.type).toBe("time");
+ });
+});
+
+describe("selection that matches nothing, and date bars", () => {
+ const bars = {
+ xAxis: { type: "category", data: ["East", "West"] },
+ series: [{ type: "bar", data: [1, 2] }],
+ };
+
+ test("a selected name not in the data leaves the chart undimmed", () => {
+ expect(applySelectionEmphasis(bars, "North")).toBe(bars);
+ });
+
+ test("a matching name still dims the rest", () => {
+ const out = applySelectionEmphasis(bars, "West") as unknown as {
+ series: { data: { itemStyle: { opacity: number } }[] }[];
+ };
+ expect(out.series[0].data.map((d) => d.itemStyle.opacity)).toEqual([
+ 0.3, 1,
+ ]);
+ });
+
+ test("a date selection matches bars over dates", () => {
+ const jan1 = new Date(2026, 0, 1).getTime();
+ const jan2 = new Date(2026, 0, 2).getTime();
+ const dateBars = {
+ xAxis: { type: "category", data: [jan1, jan2] },
+ series: [{ type: "bar", data: [1, 2] }],
+ };
+ const out = applySelectionEmphasis(dateBars, "2026-01-02") as unknown as {
+ series: { data: { itemStyle: { opacity: number } }[] }[];
+ };
+ expect(out.series[0].data.map((d) => d.itemStyle.opacity)).toEqual([
+ 0.3, 1,
+ ]);
+ });
+
+ test("a pie selection not in the slices leaves the pie undimmed", () => {
+ const pie = {
+ series: [{ type: "pie", data: [{ name: "A", value: 1 }] }],
+ };
+ expect(applySelectionEmphasis(pie, "Z")).toBe(pie);
+ });
+});
+
+describe("a single data point", () => {
+ test("line and area show the symbol of a one-point series", () => {
+ for (const chartType of ["line", "area"] as const) {
+ const option = cartesian({
+ chartType,
+ xData: ["Jan"],
+ yDataMap: { a: [5] },
+ yFields: ["a"],
+ });
+ expect(option.series[0].showSymbol).toBe(true);
+ }
+ });
+
+ test("a series with several points keeps showSymbol off", () => {
+ const option = cartesian({ chartType: "line", yFields: ["a"] });
+ expect(option.series[0].showSymbol).toBe(false);
+ });
+
+ test("a single date pads the time axis by a day", () => {
+ const day = new Date(2026, 0, 1).getTime();
+ const option = cartesian({
+ chartType: "line",
+ xData: [day],
+ yDataMap: { a: [5] },
+ yFields: ["a"],
+ isTimeSeries: true,
+ xDateOnly: true,
+ }) as unknown as { xAxis: Record };
+ expect(option.xAxis.min).toBe(day - 86400000);
+ expect(option.xAxis.max).toBe(day + 86400000);
+ expect(option.xAxis.minInterval).toBe(86400000);
+ });
+
+ test("a single bar is capped in width", () => {
+ const option = cartesian({
+ xData: ["Only"],
+ yDataMap: { a: [5] },
+ yFields: ["a"],
+ });
+ expect(option.series[0].barMaxWidth).toBe(80);
+ });
+});
+
+describe("scatter axes and tooltip", () => {
+ const scatter = () =>
+ cartesian({
+ chartType: "scatter",
+ xData: [5000, 5500, 6000],
+ yDataMap: { uptime_pct: [97, 98.5, 99.5] },
+ yFields: ["uptime_pct"],
+ xField: "monthly_spend",
+ }) as unknown as {
+ xAxis: { scale?: boolean };
+ yAxis: { scale?: boolean };
+ tooltip: { formatter: (p: unknown) => string };
+ };
+
+ test("both axes fit the data", () => {
+ const option = scatter();
+ expect(option.xAxis.scale).toBe(true);
+ expect(option.yAxis.scale).toBe(true);
+ });
+
+ test("the tooltip shows both fields", () => {
+ const text = scatter().tooltip.formatter({
+ seriesName: "Uptime Pct",
+ seriesIndex: 0,
+ value: [5500, 98.5],
+ });
+ expect(text).toContain("5500");
+ expect(text).toContain("98.5");
+ expect(text).toMatch(/Monthly Spend: 5500/);
+ });
+
+ test("bar value axes still start at 0", () => {
+ const option = cartesian() as unknown as { yAxis: { scale?: boolean } };
+ expect(option.yAxis.scale).toBeUndefined();
+ });
+});
+
+describe("scatter point opacity", () => {
+ const opacityFor = (count: number) => {
+ const xs = Array.from({ length: count }, (_, i) => i);
+ const option = cartesian({
+ chartType: "scatter",
+ xData: xs,
+ yDataMap: { a: xs },
+ yFields: ["a"],
+ });
+ return (option.series[0].itemStyle as { opacity: number }).opacity;
+ };
+
+ test("falls as the point count grows", () => {
+ expect(opacityFor(20)).toBe(0.8);
+ expect(opacityFor(200)).toBe(0.6);
+ expect(opacityFor(2000)).toBe(0.35);
+ expect(opacityFor(10000)).toBe(0.2);
+ });
+});
+
+describe("value labels", () => {
+ type Label = {
+ show: boolean;
+ position: string;
+ formatter: (p: { value: unknown }) => string;
+ };
+
+ test("bars print their values on top", () => {
+ const option = cartesian({ yFields: ["a"], showValues: true });
+ const label = option.series[0].label as Label;
+ expect(label.position).toBe("top");
+ expect(label.formatter({ value: 3 })).toBe("3");
+ });
+
+ test("stacked bars print inside, formatted like the axis", () => {
+ const option = cartesian({
+ showValues: true,
+ stacked: true,
+ axisValueFormatter: (v) => `${v} pts`,
+ });
+ const label = option.series[0].label as Label;
+ expect(label.position).toBe("inside");
+ expect(label.formatter({ value: 4 })).toBe("4 pts");
+ });
+
+ test("scatter points print y", () => {
+ const option = cartesian({
+ chartType: "scatter",
+ xData: [1, 2],
+ yDataMap: { a: [3, 4] },
+ yFields: ["a"],
+ showValues: true,
+ });
+ expect((option.series[0].label as Label).formatter({ value: [1, 3] })).toBe(
+ "3",
+ );
+ });
+
+ test("off by default and never on lines", () => {
+ expect(cartesian().series[0].label).toBeUndefined();
+ expect(
+ cartesian({ chartType: "line", showValues: true }).series[0].label,
+ ).toBeUndefined();
+ });
+
+ test("horizontal bars print to the right", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { a: [1] },
+ yFields: ["a"],
+ colors: ["#ff0000"],
+ showLegend: false,
+ showValues: true,
+ },
+ false,
+ ) as { series: { label: Label }[] };
+ expect(option.series[0].label.position).toBe("right");
+ });
+});
+
+describe("combo charts and a second y axis", () => {
+ test("a yKey drawn as a line on the right axis", () => {
+ const option = cartesian({
+ yFields: ["revenue", "margin_pct"],
+ yDataMap: { revenue: [100, 200, 300], margin_pct: [10, 12, 9] },
+ seriesConfig: { margin_pct: { type: "line", axis: "right" } },
+ }) as unknown as {
+ yAxis: Record[];
+ series: Record[];
+ };
+ expect(option.yAxis).toHaveLength(2);
+ expect(option.yAxis[1]).toMatchObject({
+ type: "value",
+ position: "right",
+ splitLine: { show: false },
+ });
+ expect(option.series[0]).toMatchObject({ type: "bar" });
+ expect(option.series[0]).not.toHaveProperty("yAxisIndex");
+ expect(option.series[1]).toMatchObject({
+ type: "line",
+ yAxisIndex: 1,
+ smooth: false,
+ });
+ });
+
+ test("without series config there is one value axis", () => {
+ const option = cartesian() as unknown as { yAxis: unknown };
+ expect(Array.isArray(option.yAxis)).toBe(false);
+ });
+
+ test("stacked bars stack per axis when series are configured", () => {
+ const option = cartesian({
+ stacked: true,
+ seriesConfig: { b: { axis: "left" } },
+ });
+ expect(option.series.map((s) => s.stack)).toEqual(["bar-left", "bar-left"]);
+ });
+});
+
+describe("reference lines widen the value axis", () => {
+ type Range = {
+ max?: (e: { min: number; max: number }) => number | undefined;
+ min?: (e: { min: number; max: number }) => number | undefined;
+ };
+ const yAxis = (o: Option) => o.yAxis as unknown as Range;
+
+ test("a line above the data raises the axis max past the line", () => {
+ const option = cartesian({ referenceLines: [{ value: 110 }] });
+ expect(yAxis(option).max?.({ min: 0, max: 98 })).toBe(120);
+ });
+
+ test("a line inside the data leaves the max to ECharts", () => {
+ const option = cartesian({ referenceLines: [{ value: 40 }] });
+ expect(yAxis(option).max?.({ min: 0, max: 98 })).toBeUndefined();
+ });
+
+ test("a line below zero lowers the min; bars still start at zero", () => {
+ const option = cartesian({ referenceLines: [{ value: -20 }] });
+ expect(yAxis(option).min?.({ min: 5, max: 98 })).toBeLessThan(-20);
+ const inside = cartesian({ referenceLines: [{ value: 3 }] });
+ expect(yAxis(inside).min?.({ min: 5, max: 98 })).toBeUndefined();
+ });
+
+ test("a line just under a positive data minimum keeps its place in the axis", () => {
+ const option = cartesian({
+ chartType: "scatter",
+ referenceLines: [{ value: 7.9 }],
+ });
+ const min = yAxis(option).min?.({ min: 8, max: 8.5 });
+ expect(min).toBeDefined();
+ expect(min as number).toBeLessThanOrEqual(7.9);
+ });
+
+ test("without reference lines the axis has no min or max", () => {
+ expect(yAxis(cartesian()).max).toBeUndefined();
+ });
+
+ test("horizontal bars widen the x axis", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { v: [50] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ referenceLines: [{ value: 400 }],
+ },
+ false,
+ ) as unknown as { xAxis: Range };
+ expect(option.xAxis.max?.({ min: 0, max: 50 })).toBeGreaterThan(400);
+ });
+});
+
+describe("title width", () => {
+ type Title = { textStyle: { width?: number; overflow?: string } };
+
+ test("a title is truncated to the card width", () => {
+ const option = cartesian({ title: "A very long title", chartWidth: 280 });
+ const title = option.title as unknown as Title;
+ expect(title.textStyle.width).toBe(280 - 32);
+ expect(title.textStyle.overflow).toBe("truncate");
+ });
+
+ test("an unmeasured chart keeps the plain title", () => {
+ const title = cartesian({ title: "T" }).title as unknown as Title;
+ expect(title.textStyle.width).toBeUndefined();
+ });
+});
+
+describe("room for the title", () => {
+ const top = (o: Option) => (o.grid as { top: unknown }).top;
+
+ test("a short chart reserves at least 44 px for the title", () => {
+ expect(top(cartesian({ title: "T", chartHeight: 200 }))).toBe(44);
+ });
+
+ test("a tall chart keeps 15% of the height", () => {
+ expect(top(cartesian({ title: "T", chartHeight: 400 }))).toBe(60);
+ });
+
+ test("without a measured height the old share is kept", () => {
+ expect(top(cartesian({ title: "T" }))).toBe("15%");
+ });
+});
+
+describe("series legend width", () => {
+ type Legend = {
+ width?: number;
+ textStyle: { width?: number; overflow?: string };
+ };
+
+ test("a measured legend is bounded and truncates long names", () => {
+ const legend = cartesian({ chartWidth: 400 }).legend as unknown as Legend;
+ expect(legend.width).toBe(352);
+ expect(legend.textStyle.width).toBe(140);
+ expect(legend.textStyle.overflow).toBe("truncate");
+ });
+
+ test("an unmeasured legend is unchanged", () => {
+ const legend = cartesian().legend as unknown as Legend;
+ expect(legend.width).toBeUndefined();
+ expect(legend.textStyle.width).toBeUndefined();
+ });
+});
+
+describe("rotated category labels", () => {
+ const axisLabel = (o: Option) =>
+ (o.xAxis as { axisLabel: Record }).axisLabel;
+ const many = Array.from({ length: 100 }, (_, i) => `Category ${i}`);
+
+ test("rotated labels hide the ones that would overlap", () => {
+ const option = cartesian({
+ xData: many,
+ yDataMap: { a: many.map((_, i) => i) },
+ yFields: ["a"],
+ chartWidth: 600,
+ });
+ expect(axisLabel(option)).toMatchObject({
+ rotate: 45,
+ hideOverlap: true,
+ });
+ });
+
+ test("upright labels keep every label", () => {
+ const option = cartesian({ chartWidth: 600 });
+ expect(axisLabel(option).hideOverlap).toBeUndefined();
+ });
+});
+
+describe("reference line labels", () => {
+ type MarkLine = { data: { label: { position?: string } }[] };
+ const positions = (o: Option) =>
+ (o.series[0].markLine as MarkLine).data.map((d) => d.label.position);
+
+ test("v3: two close lines put their labels on opposite sides", () => {
+ const option = cartesian({
+ v3: true,
+ referenceLines: [
+ { value: 1000, label: "SLO" },
+ { value: 1040, label: "Alert" },
+ ],
+ });
+ expect(positions(option)).toEqual(["insideEndBottom", "insideEndTop"]);
+ });
+
+ test("v3: one line keeps its label above it", () => {
+ const option = cartesian({ v3: true, referenceLines: [{ value: 5 }] });
+ expect(positions(option)).toEqual(["insideEndTop"]);
+ });
+
+ test("without v3 the labels are not staggered", () => {
+ const option = cartesian({
+ referenceLines: [{ value: 1 }, { value: 2 }],
+ });
+ expect(positions(option)).toEqual([undefined, undefined]);
+ });
+});
+
+describe("unlabelled reference line format", () => {
+ type MarkLine = { data: { label: { formatter: string } }[] };
+ const formatted = (o: Option) =>
+ (o.series[0].markLine as MarkLine).data[0].label.formatter;
+
+ test("a line without a label uses the axis format, not the tooltip format", () => {
+ const option = cartesian({
+ referenceLines: [{ value: 30000000 }],
+ valueFormatter: (v) => "full " + v,
+ axisValueFormatter: (v) => "short " + v,
+ });
+ expect(formatted(option)).toBe("short 30000000");
+ });
+
+ test("a user valueFormatter still applies when there is no axis format", () => {
+ const option = cartesian({
+ referenceLines: [{ value: 5 }],
+ valueFormatter: (v) => "#" + v,
+ });
+ expect(formatted(option)).toBe("#5");
+ });
+});
+
+describe("value axis ticks", () => {
+ test("value axis labels hide ticks that overlap", () => {
+ const option = cartesian({ valueFormatter: (v) => "$" + v });
+ expect(
+ (option.yAxis as { axisLabel: { hideOverlap?: boolean } }).axisLabel,
+ ).toMatchObject({
+ hideOverlap: true,
+ });
+ });
+
+ test("horizontal bars hide overlapping x ticks too", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { v: [1] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ },
+ false,
+ ) as unknown as { xAxis: { axisLabel: { hideOverlap?: boolean } } };
+ expect(option.xAxis.axisLabel.hideOverlap).toBe(true);
+ });
+});
+
+describe("horizontal bar combo series", () => {
+ const build = (seriesConfig?: Record) =>
+ buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { revenue: [500000, 400000], margin_pct: [20, 30] },
+ yFields: ["revenue", "margin_pct"],
+ colors: ["#f00", "#0f0"],
+ showLegend: true,
+ seriesConfig,
+ },
+ false,
+ ) as unknown as {
+ xAxis: unknown;
+ series: { type: string; xAxisIndex?: number }[];
+ };
+
+ test("a line series on the right axis uses a second x axis on top", () => {
+ const option = build({ margin_pct: { type: "line", axis: "right" } });
+ expect(option.series.map((s) => s.type)).toEqual(["bar", "line"]);
+ expect(option.series[1].xAxisIndex).toBe(1);
+ expect(option.xAxis).toHaveLength(2);
+ expect((option.xAxis as { position?: string }[])[1].position).toBe("top");
+ });
+
+ test("without series config every series is a bar on one axis", () => {
+ const option = build();
+ expect(option.series.map((s) => s.type)).toEqual(["bar", "bar"]);
+ expect(Array.isArray(option.xAxis)).toBe(false);
+ });
+});
+
+describe("daily bars over two years", () => {
+ const days = Array.from({ length: 730 }, (_, i) => 1735689600000 + i * 864e5);
+ const daily = (chartWidth: number) =>
+ cartesian({
+ xData: days,
+ yDataMap: { a: days.map((_, i) => i) },
+ yFields: ["a"],
+ isTimeSeries: true,
+ xDateOnly: true,
+ chartWidth,
+ }) as unknown as { xAxis: { axisLabel: Record } };
+
+ test("labels are thinned to every nth date, upright", () => {
+ const label = daily(900).xAxis.axisLabel;
+ expect(label.interval).toBe(Math.ceil(72 / ((900 * 0.8) / 730)) - 1);
+ expect(label).toMatchObject({ rotate: 0, hideOverlap: true });
+ });
+
+ test("a few dates keep the regular category labels", () => {
+ const few = cartesian({
+ xData: days.slice(0, 5),
+ yDataMap: { a: [1, 2, 3, 4, 5] },
+ yFields: ["a"],
+ isTimeSeries: true,
+ xDateOnly: true,
+ chartWidth: 900,
+ }) as unknown as { xAxis: { axisLabel: Record } };
+ expect(few.xAxis.axisLabel.interval).toBe(0);
+ });
+});
+
+describe("overlapping value labels on bars", () => {
+ test("showValues hides labels that overlap", () => {
+ const option = cartesian({ showValues: true });
+ expect(option.series.map((s) => s.labelLayout)).toEqual([
+ { hideOverlap: true },
+ { hideOverlap: true },
+ ]);
+ });
+
+ test("horizontal bars hide overlapping labels too", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { v: [1] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ showValues: true,
+ },
+ false,
+ ) as unknown as { series: { labelLayout?: unknown }[] };
+ expect(option.series[0].labelLayout).toEqual({ hideOverlap: true });
+ });
+
+ test("no labelLayout without showValues", () => {
+ expect(cartesian().series[0].labelLayout).toBeUndefined();
+ });
+});
+
+describe("labels of negative bars", () => {
+ const data = (o: Option) => o.series[0].data as unknown[];
+
+ test("a negative bar's label goes below its end", () => {
+ const option = cartesian({
+ showValues: true,
+ yFields: ["a"],
+ yDataMap: { a: [5, -3, 0] },
+ });
+ expect(data(option)[1]).toMatchObject({
+ value: -3,
+ label: { position: "bottom" },
+ });
+ expect(data(option)[0]).toBe(5);
+ });
+
+ test("without showValues no label is set", () => {
+ const option = cartesian({ yFields: ["a"], yDataMap: { a: [5, -3, 0] } });
+ expect(data(option)[1]).not.toHaveProperty("label");
+ });
+
+ test("stacked labels sit inside, no label position per item", () => {
+ const option = cartesian({
+ showValues: true,
+ stacked: true,
+ yDataMap: { a: [5, -3, 0], b: [1, 2, 3] },
+ });
+ expect(data(option)[1]).not.toHaveProperty("label");
+ });
+
+ test("horizontal negative bars put the label on the left", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [4, -4] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ showValues: true,
+ },
+ false,
+ ) as unknown as { series: { data: unknown[] }[] };
+ expect(option.series[0].data[1]).toMatchObject({
+ value: -4,
+ label: { position: "left" },
+ });
+ });
+});
+
+describe("value labels at the right edge", () => {
+ const grid = (showValues: boolean, stacked = false) =>
+ (
+ buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [7450000, 12] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ showValues,
+ valueFormatter: (v) => "$" + Number(v).toLocaleString("en-US"),
+ },
+ stacked,
+ ) as unknown as { grid: { right: number } }
+ ).grid;
+
+ test("the right margin fits the widest label", () => {
+ expect(grid(true).right).toBe("$7,450,000".length * 7 + 8);
+ });
+
+ test("without showValues the margin is 24", () => {
+ expect(grid(false).right).toBe(24);
+ });
+
+ test("stacked labels sit inside, margin stays 24", () => {
+ expect(grid(true, true).right).toBe(24);
+ });
+});
+
+describe("horizontal bar row labels", () => {
+ test("row labels hide the ones that overlap", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [1, 2] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ chartWidth: 400,
+ },
+ false,
+ ) as unknown as { yAxis: { axisLabel: { hideOverlap?: boolean } } };
+ expect(option.yAxis.axisLabel.hideOverlap).toBe(true);
+ });
+});
+
+describe("time axis tick labels", () => {
+ test("a time axis hides labels that overlap", () => {
+ const option = cartesian({
+ chartType: "line",
+ isTimeSeries: true,
+ xData: [1735689600000, 1735776000000],
+ yFields: ["a"],
+ yDataMap: { a: [1, 2] },
+ }) as unknown as { xAxis: { type: string; axisLabel: object } };
+ expect(option.xAxis.type).toBe("time");
+ expect(option.xAxis.axisLabel).toMatchObject({
+ show: true,
+ hideOverlap: true,
+ });
+ });
+
+ test("a category axis is not affected", () => {
+ const label = (
+ cartesian().xAxis as { axisLabel: { hideOverlap?: boolean } }
+ ).axisLabel;
+ expect(label.hideOverlap).toBeUndefined();
+ });
+});
+
+describe("scatter point labels", () => {
+ test("showValues on a scatter hides overlapping labels", () => {
+ const option = cartesian({
+ chartType: "scatter",
+ showValues: true,
+ xData: [1, 2, 3],
+ yFields: ["a"],
+ yDataMap: { a: [1, 2, 3] },
+ });
+ expect(option.series[0].labelLayout).toEqual({ hideOverlap: true });
+ });
+});
+
+describe("scatter x ticks", () => {
+ const scatter = (xs: number[]) =>
+ cartesian({
+ chartType: "scatter",
+ xData: xs,
+ xField: "seats",
+ yFields: ["a"],
+ yDataMap: { a: xs.map(() => 1) },
+ axisValueFormatter: (v) => "c" + v,
+ }) as unknown as {
+ xAxis: { axisLabel: { formatter?: (v: number) => string } };
+ };
+
+ test("large x values get the compact axis format", () => {
+ expect(scatter([1000000, 9000000]).xAxis.axisLabel.formatter?.(2e6)).toBe(
+ "c2000000",
+ );
+ });
+
+ test("small x values (years) keep their digits", () => {
+ expect(scatter([2019, 2024]).xAxis.axisLabel.formatter).toBeUndefined();
+ });
+});
+
+describe("scatter x axis name and legend", () => {
+ const scatter = (yFields: string[]) =>
+ cartesian({
+ chartType: "scatter",
+ v3: true,
+ xData: [1, 2],
+ xField: "seats",
+ yFields,
+ yDataMap: Object.fromEntries(yFields.map((f) => [f, [1, 2]])),
+ }) as unknown as { grid: { bottom: unknown } };
+
+ test("the name gets its own band above the legend row", () => {
+ expect(scatter(["a", "b"]).grid.bottom).toBe(36 + 40);
+ });
+
+ test("without a legend the name still has room", () => {
+ expect(scatter(["a"]).grid.bottom).toBe(40);
+ });
+});
+
+describe("scatter y axis name", () => {
+ const scatter = (field: string, ys: number[], axisValueFormatter?: never) =>
+ cartesian({
+ chartType: "scatter",
+ v3: true,
+ xData: ys.map((_, i) => i),
+ xField: "x",
+ yFields: [field],
+ yDataMap: { [field]: ys },
+ chartHeight: 240,
+ axisValueFormatter,
+ }) as unknown as {
+ grid: { left: unknown };
+ yAxis: {
+ nameGap: number;
+ nameTruncate?: { maxWidth: number };
+ };
+ };
+
+ test("the gap clears the widest tick label", () => {
+ const wide = scatter("churn", [10, 1234567]).yAxis.nameGap;
+ const narrow = scatter("churn", [1, 4]).yAxis.nameGap;
+ expect(wide).toBeGreaterThan(narrow);
+ expect(narrow).toBe(1 * 7 + 16);
+ });
+
+ test("a long name is truncated to 60% of the height", () => {
+ const axis = scatter("net_revenue_retention_pct", [1, 2]).yAxis;
+ expect(axis.nameTruncate?.maxWidth).toBe(144);
+ });
+
+ test("the left margin leaves room for the name", () => {
+ expect(scatter("churn", [1, 2]).grid.left).toBe(28);
+ });
+});
+
+describe("value label formatter", () => {
+ const label = (o: Option) =>
+ o.series[0].label as { formatter: (p: { value: unknown }) => string };
+
+ test("labels use valueLabelFormatter before the tick formatter", () => {
+ const option = cartesian({
+ showValues: true,
+ axisValueFormatter: (v) => "tick " + v,
+ valueLabelFormatter: (v) => "label " + v,
+ });
+ expect(label(option).formatter({ value: 5 })).toBe("label 5");
+ });
+
+ test("without one, labels fall back to the tick formatter", () => {
+ const option = cartesian({
+ showValues: true,
+ axisValueFormatter: (v) => "tick " + v,
+ });
+ expect(label(option).formatter({ value: 5 })).toBe("tick 5");
+ });
+});
+
+describe("stacked tooltip total", () => {
+ test("the total is free of float noise", () => {
+ const option = cartesian({
+ stacked: true,
+ yDataMap: { a: [0.1], b: [0.2] },
+ xData: ["A"],
+ yFields: ["a", "b"],
+ valueFormatter: (v) => v + "%",
+ });
+ const formatter = (
+ option.tooltip as {
+ formatter: (p: unknown) => string;
+ }
+ ).formatter;
+ const html = formatter([
+ { seriesIndex: 0, seriesName: "A", value: 0.1, axisValueLabel: "A" },
+ { seriesIndex: 1, seriesName: "B", value: 0.2, axisValueLabel: "A" },
+ { seriesIndex: 1, seriesName: "C", value: 1.1, axisValueLabel: "A" },
+ ]);
+ expect(html).toContain("Total: 1.4%");
+ expect(html).not.toContain("1.4000000000000001");
+ });
+});
+
+describe("bar rounding", () => {
+ type Item =
+ | number
+ | { value: number; itemStyle?: { borderRadius?: number[] } };
+ const radius = (s: Series, i: number) => {
+ const item = (s.data as Item[])[i];
+ return typeof item === "object" ? item.itemStyle?.borderRadius : undefined;
+ };
+ const seriesRadius = (s: Series) =>
+ (s.itemStyle as { borderRadius: number[] }).borderRadius;
+
+ test("a stack rounds only its outermost segment", () => {
+ const option = cartesian({
+ stacked: true,
+ yFields: ["a", "b", "c"],
+ yDataMap: { a: [10, 10], b: [20, 0], c: [30, 5] },
+ });
+ // Series radius is square; the top segment of each column is rounded.
+ expect(option.series.map(seriesRadius)).toEqual([
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ ]);
+ expect(radius(option.series[2], 0)).toEqual([4, 4, 0, 0]);
+ expect(radius(option.series[1], 0)).toBeUndefined();
+ expect(radius(option.series[0], 0)).toBeUndefined();
+ });
+
+ test("a zero or missing top segment hands the radius to the one below", () => {
+ const option = cartesian({
+ stacked: true,
+ yFields: ["a", "b", "c"],
+ yDataMap: { a: [10], b: [20], c: [0] },
+ xData: ["A"],
+ });
+ expect(radius(option.series[1], 0)).toEqual([4, 4, 0, 0]);
+ expect(radius(option.series[2], 0)).toBeUndefined();
+ });
+
+ test("a negative bar is rounded at its far end", () => {
+ const option = cartesian({
+ yFields: ["a"],
+ yDataMap: { a: [40, -25, 15] },
+ });
+ expect(seriesRadius(option.series[0])).toEqual([4, 4, 0, 0]);
+ expect(radius(option.series[0], 1)).toEqual([0, 0, 4, 4]);
+ expect(radius(option.series[0], 0)).toBeUndefined();
+ });
+
+ test("a mixed-sign stack rounds the outer end on each side", () => {
+ const option = cartesian({
+ stacked: true,
+ yFields: ["a", "b", "c"],
+ xData: ["A"],
+ yDataMap: { a: [10], b: [-5], c: [-7] },
+ });
+ expect(radius(option.series[0], 0)).toEqual([4, 4, 0, 0]);
+ expect(radius(option.series[1], 0)).toBeUndefined();
+ expect(radius(option.series[2], 0)).toEqual([0, 0, 4, 4]);
+ });
+
+ test("horizontal bars round the right end, or the left for negatives", () => {
+ const option = buildHorizontalBarOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { a: [4, -4], b: [3, 2] },
+ yFields: ["a", "b"],
+ colors: ["#f00", "#0f0"],
+ showLegend: true,
+ },
+ true,
+ ) as unknown as { series: Series[] };
+ expect(radius(option.series[1], 0)).toEqual([0, 4, 4, 0]);
+ expect(radius(option.series[0], 1)).toEqual([4, 0, 0, 4]);
+ });
+
+ test("an unstacked positive bar keeps the series radius", () => {
+ const option = cartesian();
+ expect(seriesRadius(option.series[0])).toEqual([4, 4, 0, 0]);
+ expect(option.series[0].data).toEqual([1, 2, 3]);
+ });
+
+ test("a series radius from options removes the per-item radii", () => {
+ const built = cartesian({ yFields: ["a"], yDataMap: { a: [4, -4] } });
+ const merged = mergeChartOptions(built, {
+ series: [{ itemStyle: { borderRadius: 0 } }],
+ }) as unknown as Option;
+ expect(radius(merged.series[0], 1)).toBeUndefined();
+ expect(seriesRadius(merged.series[0])).toBe(0 as unknown as number[]);
+ });
+});
+
+describe("options patches replace component lists", () => {
+ test("an empty series list removes every built series", () => {
+ const built = cartesian();
+ expect(built.series).toHaveLength(2);
+ const merged = mergeChartOptions(built, {
+ series: [],
+ }) as unknown as Option;
+ expect(merged.series).toEqual([]);
+ });
+
+ test("a patch with fewer entries keeps the rest of the built list", () => {
+ const merged = mergeChartOptions(cartesian(), {
+ series: [{ name: "first" }],
+ }) as unknown as Option;
+ expect(merged.series).toHaveLength(2);
+ expect(merged.series[0].name).toBe("first");
+ });
+});
+
+describe("bars clipped by the axis max", () => {
+ type Item =
+ | number
+ | { value: number; itemStyle?: { borderRadius?: number[] } };
+ const merged = (patch: Record) =>
+ mergeChartOptions(
+ cartesian({ yFields: ["a"], yDataMap: { a: [40, 64, 88] } }),
+ patch,
+ ) as unknown as Option;
+ const radius = (o: Option, i: number) => {
+ const item = (o.series[0].data as Item[])[i];
+ return typeof item === "object" ? item.itemStyle?.borderRadius : undefined;
+ };
+
+ test("a bar past a fixed axis max gets a square end", () => {
+ const option = merged({ yAxis: { max: 60 } });
+ expect(radius(option, 0)).toBeUndefined();
+ expect(radius(option, 1)).toEqual([0, 0, 0, 0]);
+ expect(radius(option, 2)).toEqual([0, 0, 0, 0]);
+ });
+
+ test("without a fixed max every bar keeps its rounded end", () => {
+ const option = merged({});
+ expect(radius(option, 2)).toBeUndefined();
+ });
+
+ test("a stack segment that crosses the max is the square one", () => {
+ const built = cartesian({
+ stacked: true,
+ yFields: ["a", "b"],
+ xData: ["A"],
+ yDataMap: { a: [40], b: [40] },
+ });
+ const option = mergeChartOptions(built, {
+ yAxis: { max: 60 },
+ }) as unknown as Option;
+ const top = (option.series[1].data as Item[])[0];
+ expect(typeof top === "object" && top.itemStyle?.borderRadius).toEqual([
+ 0, 0, 0, 0,
+ ]);
+ });
+
+ test("horizontal bars past the x axis max get a square end", () => {
+ const built = buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { a: [88] },
+ yFields: ["a"],
+ colors: ["#f00"],
+ showLegend: false,
+ },
+ false,
+ );
+ const option = mergeChartOptions(built, {
+ xAxis: { max: 60 },
+ }) as unknown as Option;
+ const item = (option.series[0].data as Item[])[0];
+ expect(typeof item === "object" && item.itemStyle?.borderRadius).toEqual([
+ 0, 0, 0, 0,
+ ]);
+ });
+});
+
+describe("rotated label interval", () => {
+ test("every nth rotated label is drawn, n from the slot width", () => {
+ const many = Array.from({ length: 100 }, (_, i) => `Category ${i}`);
+ const option = cartesian({
+ xData: many,
+ yDataMap: { a: many.map((_, i) => i) },
+ yFields: ["a"],
+ chartWidth: 600,
+ }) as unknown as { xAxis: { axisLabel: { interval: number } } };
+ // slot 4.8 px: 18 / 4.8 -> every 4th label.
+ expect(option.xAxis.axisLabel.interval).toBe(3);
+ });
+});
+
+describe("ticks of a narrow horizontal axis", () => {
+ const split = (chartWidth: number) =>
+ (
+ buildHorizontalBarOption(
+ {
+ xData: ["A"],
+ yDataMap: { v: [9000000] },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ chartWidth,
+ valueFormatter: (v) => "$" + Number(v).toLocaleString("en-US"),
+ },
+ false,
+ ) as unknown as { xAxis: { splitNumber?: number } }
+ ).xAxis.splitNumber;
+
+ test("a narrow chart gets fewer ticks for full-number labels", () => {
+ expect(split(280)).toBe(2);
+ });
+
+ test("a wide chart keeps the default tick count", () => {
+ expect(split(900)).toBeUndefined();
+ });
+});
+
+describe("row label interval", () => {
+ const interval = (rows: number, chartHeight: number) => {
+ const xData = Array.from({ length: rows }, (_, i) => `Row ${i}`);
+ return (
+ buildHorizontalBarOption(
+ {
+ xData,
+ yDataMap: { v: xData.map((_, i) => i) },
+ yFields: ["v"],
+ colors: ["#f00"],
+ showLegend: false,
+ chartHeight,
+ },
+ false,
+ ) as unknown as { yAxis: { axisLabel: { interval?: number } } }
+ ).yAxis.axisLabel.interval;
+ };
+
+ test("30 rows in 360 px draw every other label", () => {
+ // (360 - 56) / 30 = 10 px a row; 16 / 10 -> every 2nd label.
+ expect(interval(30, 360)).toBe(1);
+ });
+
+ test("rows with room keep every label", () => {
+ expect(interval(6, 360)).toBeUndefined();
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx
new file mode 100644
index 000000000..1af371c9c
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx
@@ -0,0 +1,216 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { AreaChart } from "../area";
+import { BarChart } from "../bar";
+import { LineChart } from "../line";
+import { RadarChart } from "../radar";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(installEChartsEnv);
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+const rows = [
+ { month: "Jan", revenue: 100 },
+ { month: "Feb", revenue: 120 },
+];
+
+describe("chart-specific props", () => {
+ test.each([
+ ["LineChart", LineChart],
+ ["AreaChart", AreaChart],
+ ] as const)("%s accepts symbolSize", async (_name, Chart) => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption<{ series: { symbolSize: number }[] }>(container);
+ expect(option?.series[0].symbolSize).toBe(3);
+ expect(warn.mock.calls.some((c) => String(c[0]).includes("ignores"))).toBe(
+ false,
+ );
+ });
+
+ test("a prop the chart type ignores warns in development", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const props = { min: 0, yAxisKey: "x" } as Record;
+ render(
+ ,
+ );
+ expect(
+ warn.mock.calls.some((c) =>
+ String(c[0]).includes("RadarChart ignores `min`, `yAxisKey`"),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("smooth default", () => {
+ test.each([
+ [undefined, true],
+ ["v3", false],
+ ] as const)("defaults=%s smooths: %s", async (defaults, expected) => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption<{ series: { smooth: boolean }[] }>(container);
+ expect(option?.series[0].smooth).toBe(expected);
+ });
+
+ test("an explicit smooth wins under v3", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption<{ series: { smooth: boolean }[] }>(container);
+ expect(option?.series[0].smooth).toBe(true);
+ });
+});
+
+describe("default number format", () => {
+ const big = [
+ { month: "Jan", revenue: 15234567.891 },
+ { month: "Feb", revenue: 18000000 },
+ ];
+ type Fmt = {
+ yAxis: { axisLabel: { formatter?: (v: number) => string } }[];
+ series: { tooltip?: { valueFormatter?: (v: unknown) => string } }[];
+ };
+
+ test("v3: compact ticks and full-value tooltips", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption(container);
+ expect(option?.yAxis[0].axisLabel.formatter?.(18000000)).toBe("18M");
+ expect(option?.series[0].tooltip?.valueFormatter?.(15234567.891)).toBe(
+ "15,234,567.89",
+ );
+ });
+
+ test("without v3 ticks stay raw", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption(container);
+ expect(option?.yAxis[0].axisLabel.formatter).toBeUndefined();
+ });
+
+ test("a valueFormatter wins under v3", async () => {
+ const { container } = render(
+ "USD " + String(v)}
+ />,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption(container);
+ expect(option?.yAxis[0].axisLabel.formatter?.(5)).toBe("USD 5");
+ });
+});
+
+describe("default accessible name", () => {
+ test("built from the chart type and fields", () => {
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("img").getAttribute("aria-label")).toBe(
+ "Line chart of revenue by month",
+ );
+ });
+
+ test("uses the title when given", () => {
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("img").getAttribute("aria-label")).toBe(
+ "Area chart: Revenue",
+ );
+ });
+
+ test("an explicit ariaLabel wins", () => {
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("img").getAttribute("aria-label")).toBe("Trend");
+ });
+});
+
+describe("combo chart renders", () => {
+ test("bars with a line on a second axis", async () => {
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ const option = chartOption<{
+ yAxis: unknown[];
+ series: { type: string; yAxisIndex: number }[];
+ }>(container);
+ expect(option?.yAxis).toHaveLength(2);
+ expect(option?.series.map((s) => s.type)).toEqual(["bar", "line"]);
+ expect(option?.series[1].yAxisIndex).toBe(1);
+ });
+});
+
+describe("many series", () => {
+ const rows = ["Jan", "Feb"].map((month, m) => {
+ const row: Record = { month };
+ for (let i = 1; i <= 12; i++) row[`s${i}`] = i + m;
+ return row;
+ });
+ const keys = Array.from({ length: 12 }, (_, i) => `s${i + 1}`);
+
+ test("the legend scrolls in one row and a warning says colors repeat", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { container } = render(
+ ,
+ );
+ const option = await waitFor(() => {
+ const o = chartOption<{
+ legend: { type: string }[];
+ grid: { bottom: unknown }[];
+ }>(container);
+ expect(o).toBeDefined();
+ return o as NonNullable;
+ });
+ expect(option.legend[0].type).toBe("scroll");
+ expect(option.grid[0].bottom).toBe(36);
+ expect(
+ warn.mock.calls.some(([m]) => String(m).includes("colors repeat")),
+ ).toBe(true);
+ warn.mockRestore();
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/click.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/click.test.tsx
new file mode 100644
index 000000000..838edd15b
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/click.test.tsx
@@ -0,0 +1,172 @@
+import { render, waitFor } from "@testing-library/react";
+import * as echarts from "echarts/core";
+import { beforeAll, describe, expect, test, vi } from "vitest";
+
+import { BaseChart } from "../base";
+import { nearestRadarIndicator, resolveClickDatum } from "../click";
+import type { ChartClickDatum } from "../types";
+import { installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+
+function datum(overrides: Partial): ChartClickDatum {
+ return {
+ name: "",
+ value: null,
+ dataIndex: 0,
+ seriesIndex: 0,
+ raw: {},
+ ...overrides,
+ };
+}
+
+describe("resolveClickDatum", () => {
+ test("a bar on a date axis reports the original date and its row", () => {
+ const data = [
+ { day: "2026-01-03", n: 3 },
+ { day: "2026-01-01", n: 1 },
+ ];
+ const result = resolveClickDatum(datum({ name: "", dataIndex: 0 }), {
+ chartType: "bar",
+ data,
+ xField: "day",
+ yFields: ["n"],
+ xData: [Date.UTC(2026, 0, 1), Date.UTC(2026, 0, 3)],
+ rowIndex: [1, 0],
+ seriesLabels: ["N"],
+ });
+ expect(result.name).toBe("2026-01-01");
+ expect(result.row).toBe(data[1]);
+ });
+
+ test("a scatter point maps back to its source row, not plot order", () => {
+ const data = [
+ { x: 5, y: null },
+ { x: 9, y: 2 },
+ { x: 1, y: 4 },
+ ];
+ const result = resolveClickDatum(datum({ dataIndex: 1 }), {
+ chartType: "scatter",
+ data,
+ xField: "x",
+ yFields: ["y"],
+ // sorted by x: rows 2, 0, 1
+ xData: [1, 5, 9],
+ yDataMap: { y: [4, null, 2] },
+ rowIndex: [2, 0, 1],
+ seriesLabels: ["Y"],
+ });
+ expect(result.row).toBe(data[1]);
+ expect(result.dataIndex).toBe(1);
+ });
+
+ test("pie and heatmap placeholders never reach seriesName", () => {
+ const data = [{ seg: "A", v: 1 }];
+ const pie = resolveClickDatum(
+ datum({
+ name: "A",
+ seriesName: "\u0000series\u00000\u00000",
+ raw: { data: { sourceIndex: 0 } },
+ }),
+ {
+ chartType: "pie",
+ data,
+ xField: "seg",
+ yFields: ["v"],
+ xData: ["A"],
+ rowIndex: [0],
+ seriesLabels: ["V"],
+ },
+ );
+ expect(pie.seriesName).toBeUndefined();
+ expect(pie.name).toBe("A");
+ expect(pie.row).toBe(data[0]);
+ });
+
+ test("a radar click names the nearest metric and its value", () => {
+ const data = [
+ { metric: "speed", a: 1 },
+ { metric: "power", a: 2 },
+ { metric: "range", a: 3 },
+ { metric: "cost", a: 4 },
+ ];
+ const ctx = {
+ chartType: "radar",
+ data,
+ xField: "metric",
+ yFields: ["a"],
+ xData: ["speed", "power", "range", "cost"],
+ yDataMap: { a: [1, 2, 3, 4] },
+ rowIndex: [0, 1, 2, 3],
+ seriesLabels: ["A"],
+ };
+ // Spokes: 0 up, 1 left, 2 down, 3 right (counter-clockwise from 90°).
+ const left = resolveClickDatum(
+ datum({ seriesName: "\u0000series\u00000\u00000" }),
+ ctx,
+ { width: 200, height: 200 },
+ { x: 20, y: 100 },
+ );
+ expect(left.name).toBe("power");
+ expect(left.value).toBe(2);
+ expect(left.seriesName).toBe("A");
+ expect(left.row).toBe(data[1]);
+ });
+});
+
+describe("nearestRadarIndicator", () => {
+ test("honours clockwise layout", () => {
+ expect(
+ nearestRadarIndicator(20, 100, 4, {
+ width: 200,
+ height: 200,
+ clockwise: true,
+ }),
+ ).toBe(3);
+ });
+});
+
+describe("BaseChart onDataClick", () => {
+ test("a click on a date bar returns the date string and the row", async () => {
+ const onDataClick = vi.fn();
+ const data = [
+ { day: "2026-01-02", orders: 5 },
+ { day: "2026-01-01", orders: 3 },
+ ];
+ const { container } = render(
+ ,
+ );
+ const element = await waitFor(() => {
+ const el = container.querySelector(".echarts-for-react");
+ expect(el).not.toBeNull();
+ return el as HTMLElement;
+ });
+ const instance = await waitFor(() => {
+ type Instance = {
+ trigger(name: string, params: unknown): void;
+ isSilent(name: string): boolean;
+ };
+ const current = echarts.getInstanceByDom(element) as unknown as
+ | Instance
+ | undefined;
+ expect(current?.isSilent("click")).toBe(false);
+ return current as Instance;
+ });
+ instance.trigger("click", {
+ seriesType: "bar",
+ seriesIndex: 0,
+ dataIndex: 0,
+ name: "",
+ value: 3,
+ });
+ expect(onDataClick).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "2026-01-01", row: data[1] }),
+ );
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/examples.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/examples.test.tsx
new file mode 100644
index 000000000..46ca2c622
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/examples.test.tsx
@@ -0,0 +1,62 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import DataTableExample from "../../table/examples/data-table.example";
+import AreaExample from "../area/examples/area.example";
+import BarExample from "../bar/examples/bar.example";
+import HeatmapExample from "../heatmap/examples/heatmap.example";
+import LineExample from "../line/examples/line.example";
+import DonutExample from "../pie/examples/donut.example";
+import PieExample from "../pie/examples/pie.example";
+import RadarExample from "../radar/examples/radar.example";
+import ScatterExample from "../scatter/examples/scatter.example";
+import { installEChartsEnv } from "./helpers/echarts-env";
+
+const examples = {
+ area: AreaExample,
+ bar: BarExample,
+ heatmap: HeatmapExample,
+ line: LineExample,
+ donut: DonutExample,
+ pie: PieExample,
+ radar: RadarExample,
+ scatter: ScatterExample,
+ "data-table": DataTableExample,
+};
+
+beforeAll(() => {
+ installEChartsEnv();
+ globalThis.ResizeObserver ??= class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ } as unknown as typeof ResizeObserver;
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("documented examples", () => {
+ test("covers every chart and the table", () => {
+ expect(Object.keys(examples).length).toBe(9);
+ });
+
+ test.each(Object.entries(examples))(
+ "%s renders without errors or warnings",
+ (_name, Example) => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ render();
+ expect(screen.queryByText(/Failed to render|No data/)).toBeNull();
+ expect(error).not.toHaveBeenCalled();
+ // jsdom has no layout, so ECharts always reports a 0x0 box; any other
+ // warning (unknown key, ignored prop, mixed signs, ...) is a bad example.
+ const warnings = warn.mock.calls.filter(
+ ([message]) => !String(message).startsWith("[ECharts] Can't get DOM"),
+ );
+ expect(warnings).toEqual([]);
+ },
+ );
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx
new file mode 100644
index 000000000..e9bdef9db
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx
@@ -0,0 +1,130 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { HeatmapChart } from "../heatmap";
+import { normalizeHeatmapData } from "../normalize";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+const rows = [
+ { hour: 9, day: "Mon", orders: 4 },
+ { hour: 10, day: "Tue", orders: 7 },
+];
+
+describe("heatmap keys", () => {
+ test("yKey used as the row dimension is reported", () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain("holds text");
+ });
+
+ test("a mistyped yAxisKey is reported", () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain('yAxisKey "dya"');
+ });
+
+ test("columnKey, rowKey and valueKey name the three roles", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await waitFor(() => {
+ const o = chartOption<{
+ xAxis: { data: unknown[] }[];
+ yAxis: { data: unknown[] }[];
+ }>(container);
+ expect(o).toBeDefined();
+ return o as NonNullable;
+ });
+ expect(option.xAxis[0].data).toEqual([9, 10]);
+ expect(option.yAxis[0].data).toEqual(["Mon", "Tue"]);
+ });
+
+ test("without keys the value is the numeric column, not the third one", () => {
+ const norm = normalizeHeatmapData(
+ [{ orders: 4, day: "Mon", hour_label: "9am" }],
+ undefined,
+ undefined,
+ undefined,
+ );
+ expect(norm.yFields).toEqual(["orders"]);
+ expect(norm.xField).toBe("day");
+ });
+});
+
+describe("diverging heatmap", () => {
+ test("the color scale is centred on zero", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await waitFor(() => {
+ const o = chartOption<{ visualMap: { min: number; max: number }[] }>(
+ container,
+ );
+ expect(o).toBeDefined();
+ return o as NonNullable;
+ });
+ expect(option.visualMap[0]).toMatchObject({ min: -40, max: 40 });
+ });
+});
+
+describe("heatmap", () => {
+ async function visualMap(container: HTMLElement) {
+ return waitFor(() => {
+ const o = chartOption<{
+ visualMap: { min: number; max: number; inRange: { color: string[] } }[];
+ }>(container);
+ expect(o).toBeDefined();
+ return (o as NonNullable).visualMap[0];
+ });
+ }
+
+ test("all-equal values get a padded scale", async () => {
+ const { container } = render(
+ ,
+ );
+ expect(await visualMap(container)).toMatchObject({ min: 6, max: 8 });
+ });
+
+ test("a categorical palette falls back to sequential with a warning", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const props = { data: rows, xKey: "hour", yAxisKey: "day", yKey: "orders" };
+ const cat = render();
+ const seq = render();
+ const a = await visualMap(cat.container);
+ const b = await visualMap(seq.container);
+ expect(a.inRange.color).toEqual(b.inRange.color);
+ expect(warn).toHaveBeenCalled();
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts
new file mode 100644
index 000000000..70da57a2b
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+
+import { normalizeHeatmapData } from "../normalize";
+import { buildHeatmapOption } from "../options";
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("heatmap axis order", () => {
+ test("weekdays and hours are put in order, other text keeps row order", () => {
+ const rows = [
+ { day: "Wed", hour: 14, n: 1 },
+ { day: "Mon", hour: 9, n: 2 },
+ { day: "Sun", hour: 2, n: 3 },
+ { day: "Tue", hour: 9, n: 4 },
+ ];
+ const norm = normalizeHeatmapData(rows, "hour", "day", "n");
+ expect(norm.xData).toEqual([2, 9, 14]);
+ expect(norm.yAxisData).toEqual(["Mon", "Tue", "Wed", "Sun"]);
+
+ const regions = normalizeHeatmapData(
+ [
+ { region: "West", q: "Q1", n: 1 },
+ { region: "East", q: "Q1", n: 1 },
+ ],
+ "q",
+ "region",
+ "n",
+ );
+ expect(regions.yAxisData).toEqual(["West", "East"]);
+ });
+
+ test("xOrder and yOrder override the order", () => {
+ const norm = normalizeHeatmapData(
+ [
+ { a: "low", b: "x", n: 1 },
+ { a: "high", b: "x", n: 1 },
+ { a: "mid", b: "x", n: 1 },
+ ],
+ "a",
+ "b",
+ "n",
+ { xOrder: ["low", "mid", "high"] },
+ );
+ expect(norm.xData).toEqual(["low", "mid", "high"]);
+ });
+
+ test("repeated cells are summed with a warning", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const norm = normalizeHeatmapData(
+ [
+ { d: "Mon", h: 1, n: 2 },
+ { d: "Mon", h: 1, n: 3 },
+ ],
+ "h",
+ "d",
+ "n",
+ );
+ expect(norm.heatmapData).toEqual([[0, 0, 5]]);
+ expect(norm.max).toBe(5);
+ expect(warn).toHaveBeenCalled();
+ });
+});
+
+describe("heatmap labels", () => {
+ const ctx = (columns: number, rows: number, chartWidth?: number) => ({
+ xData: Array.from({ length: columns }, (_, i) => i),
+ yAxisData: Array.from({ length: rows }, (_, i) => `r${i}`),
+ heatmapData: [[0, 0, 1]] as [number, number, number][],
+ yDataMap: {},
+ yFields: ["n"],
+ colors: ["#eee", "#111"],
+ showLegend: true,
+ min: 0,
+ max: 1,
+ chartWidth,
+ });
+ const shown = (opt: unknown) =>
+ (opt as { series: { label: { show: boolean } }[] }).series[0].label.show;
+
+ test("on for a small grid, off for 7 x 24 and for narrow cells", () => {
+ expect(shown(buildHeatmapOption(ctx(5, 5)))).toBe(true);
+ expect(shown(buildHeatmapOption(ctx(24, 7)))).toBe(false);
+ expect(shown(buildHeatmapOption(ctx(10, 5, 280)))).toBe(false);
+ expect(shown(buildHeatmapOption({ ...ctx(24, 7), showLabels: true }))).toBe(
+ true,
+ );
+ });
+});
+
+describe("heatmap color scale", () => {
+ const base = {
+ xData: ["a", "b"],
+ yAxisData: ["r"],
+ heatmapData: [[0, 0, 1]] as [number, number, number][],
+ yDataMap: {},
+ yFields: ["n"],
+ colors: ["#eee", "#111"],
+ showLegend: true,
+ min: 0,
+ max: 12000,
+ };
+ type Opt = {
+ grid: { right: number; containLabel: boolean };
+ visualMap: { show: boolean; calculable: boolean };
+ };
+
+ test("space is reserved for the scale and its labels; no drag handles", () => {
+ const opt = buildHeatmapOption(base) as unknown as Opt;
+ expect(opt.grid.containLabel).toBe(true);
+ // 14 bar + 8 gap + 5 chars x 7 + 16
+ expect(opt.grid.right).toBe(73);
+ expect(opt.visualMap.calculable).toBe(false);
+ });
+
+ test("showLegend={false} hides the scale", () => {
+ const opt = buildHeatmapOption({
+ ...base,
+ showLegend: false,
+ }) as unknown as Opt;
+ expect(opt.visualMap.show).toBe(false);
+ expect(opt.grid.right).toBe(16);
+ });
+});
+
+describe("colour scale numbers", () => {
+ test("the scale prints its largest and smallest value", async () => {
+ const { buildHeatmapOption } = await import("../options");
+ const option = buildHeatmapOption({
+ xData: ["a", "b"],
+ yAxisData: ["x"],
+ heatmapData: [
+ [0, 0, 5],
+ [1, 0, 95],
+ ],
+ min: 5,
+ max: 95,
+ yDataMap: {},
+ yFields: ["v"],
+ colors: ["#fff", "#000"],
+ showLegend: true,
+ valueFormatter: (v) => v + "%",
+ }) as unknown as { visualMap: { text: string[]; calculable: boolean } };
+ expect(option.visualMap.text).toEqual(["95%", "5%"]);
+ expect(option.visualMap.calculable).toBe(false);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/helpers/echarts-env.ts b/packages/appkit-ui/src/react/charts/__tests__/helpers/echarts-env.ts
new file mode 100644
index 000000000..fea62acdd
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/helpers/echarts-env.ts
@@ -0,0 +1,57 @@
+/**
+ * jsdom setup for tests that mount real ECharts instances, plus a helper that
+ * reads the option a mounted chart is rendering.
+ */
+import * as echarts from "echarts/core";
+import { vi } from "vitest";
+
+/** Stubs `matchMedia` and the canvas 2D context, which jsdom lacks. */
+export function installEChartsEnv() {
+ if (!window.matchMedia) {
+ Object.defineProperty(window, "matchMedia", {
+ writable: true,
+ value: (query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ });
+ }
+ const contextStub = new Proxy(
+ {},
+ {
+ get(target: Record, prop: string) {
+ if (prop === "measureText") return () => ({ width: 10 });
+ if (
+ prop === "createLinearGradient" ||
+ prop === "createRadialGradient"
+ ) {
+ return () => ({ addColorStop: () => {} });
+ }
+ if (!(prop in target)) target[prop] = vi.fn();
+ return target[prop];
+ },
+ set() {
+ return true;
+ },
+ },
+ );
+ Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
+ writable: true,
+ value: () => contextStub,
+ });
+}
+
+/** The option the chart inside `container` renders, or undefined before mount. */
+export function chartOption>(
+ container: HTMLElement,
+): T | undefined {
+ const root = container.querySelector("[_echarts_instance_]");
+ if (!(root instanceof HTMLElement)) return undefined;
+ return echarts.getInstanceByDom(root)?.getOption() as T | undefined;
+}
diff --git a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts
index 505265015..fc1ad022f 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts
+++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } from "vitest";
import { normalizeChartData, normalizeHeatmapData } from "../normalize";
@@ -279,7 +279,7 @@ describe("normalizeChartData", () => {
expect(result.yDataMap.value[2]).toBe(200.5);
});
- test("handles null x-values as empty string", () => {
+ test('labels null x-values "(null)"', () => {
const data = [
{ name: null, value: 100 },
{ name: "B", value: 200 },
@@ -287,7 +287,7 @@ describe("normalizeChartData", () => {
const result = normalizeChartData(data);
- expect(result.xData[0]).toBe("");
+ expect(result.xData[0]).toBe("(null)");
expect(result.xData[1]).toBe("B");
});
@@ -506,3 +506,316 @@ describe("normalizeHeatmapData", () => {
expect(result.max).toBe(42);
});
});
+
+describe("x axis type from the xKey values", () => {
+ test("a measure whose name contains `time` does not make a time axis", () => {
+ const data = [
+ { category: "A", avg_response_time: 12 },
+ { category: "B", avg_response_time: 15 },
+ ];
+ const result = normalizeChartData(data, "category", "avg_response_time");
+ expect(result.chartType).toBe("categorical");
+ expect(result.xAxisType).toBe("category");
+ expect(result.xData).toEqual(["A", "B"]);
+ });
+
+ test.each(["previous_period", "lifetime_value", "update_count"])(
+ "an unused column named %s does not change the axis",
+ (extra) => {
+ const data = [
+ { region: "East", revenue: 10, [extra]: 1 },
+ { region: "West", revenue: 20, [extra]: 2 },
+ ];
+ expect(normalizeChartData(data, "region", "revenue").chartType).toBe(
+ "categorical",
+ );
+ },
+ );
+
+ test("an unused column that holds dates does not change the axis", () => {
+ const data = [
+ { region: "East", revenue: 10, as_of: "2026-01-01" },
+ { region: "West", revenue: 20, as_of: "2026-01-02" },
+ ];
+ const result = normalizeChartData(data, "region", "revenue");
+ expect(result.chartType).toBe("categorical");
+ expect(result.xData).toEqual(["East", "West"]);
+ });
+
+ test("an xKey that holds dates gives a time axis whatever its name", () => {
+ const data = [
+ { bucket: "2026-01-02", n: 2 },
+ { bucket: "2026-01-01", n: 1 },
+ ];
+ const result = normalizeChartData(data, "bucket", "n");
+ expect(result.chartType).toBe("timeseries");
+ expect(result.yDataMap.n).toEqual([1, 2]);
+ });
+
+ test("xType overrides the inferred type", () => {
+ const data = [
+ { day: "2026-01-01", n: 1 },
+ { day: "2026-01-02", n: 2 },
+ ];
+ const result = normalizeChartData(data, "day", "n", undefined, {
+ xType: "category",
+ });
+ expect(result.chartType).toBe("categorical");
+ expect(result.xAxisType).toBe("category");
+ expect(result.xData).toEqual(["2026-01-01", "2026-01-02"]);
+ });
+});
+
+describe("axis type ignores column names and the first row", () => {
+ test.each(["month", "period"])(
+ "YYYY-MM strings under %s are categories",
+ (key) => {
+ const data = [
+ { [key]: "2026-01", n: 1 },
+ { [key]: "2026-02", n: 2 },
+ ];
+ expect(normalizeChartData(data, key, "n").chartType).toBe("categorical");
+ },
+ );
+
+ test.each(["ts", "timestamp"])(
+ "epoch numbers under %s get the same axis",
+ (key) => {
+ const data = [
+ { [key]: 1767225600000, n: 1 },
+ { [key]: 1767312000000, n: 2 },
+ ];
+ expect(normalizeChartData(data, key, "n").chartType).toBe("categorical");
+ },
+ );
+
+ test("a null in the first row keeps a date column on a time axis", () => {
+ const data = [
+ { day: null, n: 0 },
+ { day: "2026-01-01", n: 1 },
+ { day: "2026-01-02", n: 2 },
+ ];
+ expect(normalizeChartData(data, "day", "n").chartType).toBe("timeseries");
+ });
+});
+
+describe("scatter auto-detection", () => {
+ test("uptime_pct is not taken as a date column", () => {
+ const data = [
+ { customer: "a", monthly_spend: 100, uptime_pct: 99.1 },
+ { customer: "b", monthly_spend: 200, uptime_pct: 98.4 },
+ ];
+ const result = normalizeChartData(data);
+ expect(result.chartType).toBe("categorical");
+ expect(result.xField).toBe("customer");
+ expect(result.yFields).toEqual(["monthly_spend", "uptime_pct"]);
+ });
+});
+
+describe("one key given", () => {
+ const data = [
+ { monthly_spend: 100, uptime_pct: 99.1 },
+ { monthly_spend: 200, uptime_pct: 98.4 },
+ ];
+
+ test("xKey alone: y is another column", () => {
+ const result = normalizeChartData(data, "uptime_pct");
+ expect(result.xField).toBe("uptime_pct");
+ expect(result.yFields).toEqual(["monthly_spend"]);
+ });
+
+ test("yKey alone: x is another column", () => {
+ const result = normalizeChartData(data, undefined, "monthly_spend");
+ expect(result.yFields).toEqual(["monthly_spend"]);
+ expect(result.xField).toBe("uptime_pct");
+ });
+});
+
+describe("missing measures", () => {
+ const data = [
+ { day: "2026-01-01", n: 1 },
+ { day: "2026-01-02", n: null },
+ { day: "2026-01-03" },
+ { day: "2026-01-04", n: "" },
+ { day: "2026-01-05", n: 5 },
+ ];
+
+ test("without v3, missing measures stay 0", () => {
+ expect(normalizeChartData(data, "day", "n").yDataMap.n).toEqual([
+ 1, 0, 0, 0, 5,
+ ]);
+ });
+
+ test("with keepNulls, missing measures are null", () => {
+ expect(
+ normalizeChartData(data, "day", "n", undefined, { keepNulls: true })
+ .yDataMap.n,
+ ).toEqual([1, null, null, null, 5]);
+ });
+
+ test("heatmap: a missing value is an empty cell with keepNulls", () => {
+ const rows = [
+ { x: "a", y: "r", v: 2 },
+ { x: "b", y: "r", v: null },
+ { x: "c", y: "r", v: 8 },
+ ];
+ const legacy = normalizeHeatmapData(rows, "x", "y", "v");
+ expect(legacy.heatmapData).toEqual([
+ [0, 0, 2],
+ [1, 0, 0],
+ [2, 0, 8],
+ ]);
+ const v3 = normalizeHeatmapData(rows, "x", "y", "v", { keepNulls: true });
+ expect(v3.heatmapData).toEqual([
+ [0, 0, 2],
+ [2, 0, 8],
+ ]);
+ expect(v3.min).toBe(2);
+ expect(v3.xData).toEqual(["a", "b", "c"]);
+ });
+});
+
+describe("heatmap non-numeric values", () => {
+ test("text and booleans are empty cells with a warning, not 0", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const rows = [
+ { x: "a", y: "r", v: 10 },
+ { x: "b", y: "r", v: "high" },
+ { x: "c", y: "r", v: true },
+ { x: "d", y: "r", v: "1,234.5" },
+ { x: "e", y: "r", v: 20 },
+ ];
+ const result = normalizeHeatmapData(rows, "x", "y", "v");
+ expect(result.heatmapData).toEqual([
+ [0, 0, 10],
+ [4, 0, 20],
+ ]);
+ expect(result.min).toBe(10);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0][0])).toContain("3 value(s)");
+ warn.mockRestore();
+ });
+});
+
+describe("category values are never rewritten or re-sorted", () => {
+ test("numeric-looking strings keep their text and row order", () => {
+ const n = normalizeChartData(
+ [
+ { code: "007", v: 7 },
+ { code: "010", v: 10 },
+ { code: "003", v: 3 },
+ ],
+ "code",
+ "v",
+ );
+ expect(n.xData).toEqual(["007", "010", "003"]);
+ expect(n.yDataMap.v).toEqual([7, 10, 3]);
+ });
+
+ test("numeric years keep the row order, with or without an Other row", () => {
+ expect(
+ normalizeChartData(
+ [
+ { year: 2024, v: 1 },
+ { year: 2022, v: 2 },
+ ],
+ "year",
+ "v",
+ ).xData,
+ ).toEqual([2024, 2022]);
+ expect(
+ normalizeChartData(
+ [
+ { year: 2024, v: 1 },
+ { year: 2022, v: 2 },
+ { year: "Other", v: 3 },
+ ],
+ "year",
+ "v",
+ ).xData,
+ ).toEqual([2024, 2022, "Other"]);
+ });
+
+ test("xType value still sorts a numeric axis", () => {
+ expect(
+ normalizeChartData(
+ [
+ { x: 3, v: 1 },
+ { x: 1, v: 2 },
+ ],
+ "x",
+ "v",
+ undefined,
+ { xType: "value" },
+ ).xData,
+ ).toEqual([1, 3]);
+ });
+
+ test("dates as category names stay text with xType category (pie, radar)", () => {
+ expect(
+ normalizeChartData(
+ [
+ { month: "2026-01-01", v: 1 },
+ { month: "2026-02-01", v: 2 },
+ ],
+ "month",
+ "v",
+ undefined,
+ { xType: "category" },
+ ).xData,
+ ).toEqual(["2026-01-01", "2026-02-01"]);
+ });
+});
+
+describe("seriesKey pivots long rows", () => {
+ const rows = [
+ { day: "2026-01-01", region: "east", revenue: 1 },
+ { day: "2026-01-01", region: "west", revenue: 2 },
+ { day: "2026-01-02", region: "east", revenue: 3 },
+ { day: "2026-01-02", region: "west", revenue: 4 },
+ { day: "2026-01-03", region: "east", revenue: 5 },
+ ];
+
+ test("one series per distinct seriesKey value", () => {
+ const n = normalizeChartData(rows, "day", "revenue", undefined, {
+ seriesKey: "region",
+ });
+ expect(n.chartType).toBe("timeseries");
+ expect(n.xData).toHaveLength(3);
+ expect(n.yFields).toEqual(["east", "west"]);
+ expect(n.yDataMap.east).toEqual([1, 3, 5]);
+ expect(n.yDataMap.west).toEqual([2, 4, 0]);
+ });
+
+ test("a missing combination is a gap with keepNulls", () => {
+ const n = normalizeChartData(rows, "day", "revenue", undefined, {
+ seriesKey: "region",
+ keepNulls: true,
+ });
+ expect(n.yDataMap.west).toEqual([2, 4, null]);
+ });
+
+ test("keys are auto-detected without the series column", () => {
+ const n = normalizeChartData(rows, undefined, undefined, undefined, {
+ seriesKey: "region",
+ });
+ expect(n.xField).toBe("day");
+ expect(n.yFields).toEqual(["east", "west"]);
+ });
+
+ test("a series named like the x column does not overwrite the x values", () => {
+ const n = normalizeChartData(
+ [
+ { region: "north", kind: "region", revenue: 1 },
+ { region: "south", kind: "region", revenue: 3 },
+ ],
+ "region",
+ "revenue",
+ undefined,
+ { seriesKey: "kind" },
+ );
+ expect(n.xField).toBe("region");
+ expect(n.xData).toEqual(["north", "south"]);
+ expect(n.yDataMap.region).toEqual([1, 3]);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts
index f111a977d..7832503a9 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts
+++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts
@@ -9,6 +9,7 @@ import {
buildPieOption,
buildRadarOption,
type HeatmapContext,
+ mergeChartOptions,
type OptionBuilderContext,
} from "../options";
@@ -193,8 +194,7 @@ describe("buildCartesianOption", () => {
expect(opt.title?.text).toBe("My Chart");
});
- test("does not apply stacking to bar charts", () => {
- // Stacking only works for area charts, not bar charts
+ test("stacks vertical bar charts when stacked", () => {
const ctx = createBaseContext({
yFields: ["a", "b"],
yDataMap: { a: [1, 2], b: [3, 4] },
@@ -211,8 +211,8 @@ describe("buildCartesianOption", () => {
}),
);
- expect(opt.series[0].stack).toBeUndefined();
- expect(opt.series[1].stack).toBeUndefined();
+ expect(opt.series[0].stack).toBe("total");
+ expect(opt.series[1].stack).toBe("total");
});
});
@@ -611,10 +611,12 @@ describe("buildPieOption", () => {
expect(opt.series[0].type).toBe("pie");
expect(opt.series[0].data).toHaveLength(3);
- // Pie data format is { name, value } without itemStyle colors
+ // Pie data format is { name, value } without itemStyle colors, plus the
+ // x position a click resolves to.
expect(opt.series[0].data[0]).toEqual({
name: "A",
value: 10,
+ sourceIndex: 0,
});
});
@@ -634,21 +636,24 @@ describe("buildPieOption", () => {
expect(opt.series[0].radius).toEqual(["50%", "70%"]);
});
- test("keeps tiny pie and donut slices pointer-selectable", () => {
+ test("draws tiny slices at their true size and leaves zero slices out", () => {
const ctx = createBaseContext({
- yDataMap: { value: [99.6, 0.4] },
- xData: ["Large", "Tiny"],
+ yDataMap: { value: [99.6, 0.4, 0] },
+ xData: ["Large", "Tiny", "Zero"],
});
const opt = asOption(buildPieOption(ctx, "donut", 50, true, "outside"));
- expect(opt.series[0].minAngle).toBe(3);
+ expect(opt.series[0].minAngle).toBeUndefined();
+ expect(opt.series[0].data).toHaveLength(2);
});
test("uses default inner radius for donut type", () => {
const ctx = createBaseContext();
- const opt = asOption(buildPieOption(ctx, "donut", 0, true, "inside"));
+ const opt = asOption(
+ buildPieOption(ctx, "donut", undefined, true, "inside"),
+ );
- // Donut type with 0 innerRadius uses 40% default
+ // Donut type without innerRadius uses 40% default
expect(opt.series[0].radius).toEqual(["40%", "70%"]);
});
@@ -714,8 +719,18 @@ describe("buildRadarOption", () => {
});
const opt = asOption(buildRadarOption(ctx, true));
- // Max should be 50 * 1.2 = 60
- expect(opt.radar?.indicator[0].max).toBe(60);
+ // One scale: the largest value rounded up to a nice number.
+ expect(opt.radar?.indicator.map((i) => i.max)).toEqual([50, 50, 50]);
+ });
+
+ test("gives each spoke its own rim when metric scales differ", () => {
+ const ctx = createBaseContext({
+ xData: ["revenue", "nps", "uptime"],
+ yDataMap: { value: [5400, 72, 0.99] },
+ });
+ const opt = asOption(buildRadarOption(ctx, true));
+
+ expect(opt.radar?.indicator.map((i) => i.max)).toEqual([6000, 80, 1]);
});
test("shows area fill when showArea=true", () => {
@@ -1353,3 +1368,392 @@ describe("applySelectionEmphasis", () => {
});
});
});
+
+describe("xType value axis", () => {
+ test("isValueX puts x on a value axis with [x, y] pairs", () => {
+ const opt = buildCartesianOption({
+ xData: [1, 2],
+ yDataMap: { y: [3, 4] },
+ yFields: ["y"],
+ colors: ["#000"],
+ showLegend: false,
+ chartType: "line",
+ isTimeSeries: false,
+ isValueX: true,
+ stacked: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 4,
+ }) as {
+ xAxis: { type: string; data?: unknown };
+ series: { data: unknown }[];
+ };
+ expect(opt.xAxis.type).toBe("value");
+ expect(opt.xAxis.data).toBeUndefined();
+ expect(opt.series[0].data).toEqual([
+ [1, 3],
+ [2, 4],
+ ]);
+ });
+});
+
+describe("connectNulls", () => {
+ const base = {
+ xData: ["a", "b", "c"],
+ yDataMap: { y: [1, null, 3] },
+ yFields: ["y"],
+ colors: ["#000"],
+ showLegend: false,
+ chartType: "line" as const,
+ isTimeSeries: false,
+ stacked: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 4,
+ };
+ type Opt = { series: { data: unknown[]; connectNulls?: boolean }[] };
+
+ test("null stays in the series data and leaves a gap by default", () => {
+ const opt = buildCartesianOption(base) as Opt;
+ expect(opt.series[0].data).toEqual([1, null, 3]);
+ expect(opt.series[0].connectNulls).toBeUndefined();
+ });
+
+ test("connectNulls draws across the gap", () => {
+ const opt = buildCartesianOption({ ...base, connectNulls: true }) as Opt;
+ expect(opt.series[0].connectNulls).toBe(true);
+ });
+});
+
+describe("scatter missing values", () => {
+ test("a point is dropped when either value is missing or not a number", () => {
+ const opt = buildCartesianOption({
+ xData: [1, "", 3, 4, 5, "6"],
+ yDataMap: { y: [10, 20, null, "", "abc", "60"] },
+ yFields: ["y"],
+ colors: ["#000"],
+ showLegend: false,
+ chartType: "scatter",
+ isTimeSeries: false,
+ stacked: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 8,
+ }) as { series: { data: unknown[] }[] };
+ expect(opt.series[0].data).toEqual([
+ [1, 10],
+ [6, 60],
+ ]);
+ });
+});
+
+describe("mergeChartOptions", () => {
+ const built = {
+ xAxis: { type: "category", data: ["a", "b"], axisLabel: { color: "#111" } },
+ yAxis: { type: "value" },
+ series: [
+ { type: "bar", data: [1, 2], name: "Revenue" },
+ { type: "bar", data: [3, 4], name: "Cost" },
+ ],
+ grid: { left: "10%" },
+ };
+
+ test("an axisLabel tweak keeps the category axis and its data", () => {
+ const out = mergeChartOptions(built, {
+ xAxis: { axisLabel: { rotate: 45 } },
+ }) as typeof built & { xAxis: { axisLabel: { rotate: number } } };
+ expect(out.xAxis.type).toBe("category");
+ expect(out.xAxis.data).toEqual(["a", "b"]);
+ expect(out.xAxis.axisLabel).toEqual({ color: "#111", rotate: 45 });
+ });
+
+ test("a series entry merges into the first series and keeps the rest", () => {
+ const out = mergeChartOptions(built, {
+ series: [{ markLine: { data: [{ yAxis: 2 }] } }],
+ }) as { series: Record[] };
+ expect(out.series).toHaveLength(2);
+ expect(out.series[0].data).toEqual([1, 2]);
+ expect(out.series[0].markLine).toEqual({ data: [{ yAxis: 2 }] });
+ expect(out.series[1].data).toEqual([3, 4]);
+ });
+
+ test("a series object applies to every series", () => {
+ const out = mergeChartOptions(built, {
+ series: { barMaxWidth: 20 },
+ }) as { series: Record[] };
+ expect(out.series.map((x) => x.barMaxWidth)).toEqual([20, 20]);
+ expect(out.series[1].name).toBe("Cost");
+ });
+
+ test("an axis array patches the built axis by index", () => {
+ const out = mergeChartOptions(built, {
+ yAxis: [{ min: 0 }],
+ }) as { yAxis: Record };
+ expect(out.yAxis).toEqual({ type: "value", min: 0 });
+ });
+
+ test("a function receives the built option", () => {
+ const out = mergeChartOptions(built, (b) => ({ ...b, animation: false }));
+ expect(out.animation).toBe(false);
+ expect(out.series).toBe(built.series);
+ });
+
+ test("no options returns the built option", () => {
+ expect(mergeChartOptions(built, undefined)).toBe(built);
+ });
+});
+
+describe("pie title", () => {
+ const pie = (overrides: Partial = {}) =>
+ buildPieOption(
+ {
+ xData: ["A", "B", "C"],
+ yDataMap: { v: [3, 2, 1] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0", "#00f"],
+ showLegend: true,
+ v3: true,
+ chartWidth: 400,
+ chartHeight: 300,
+ ...overrides,
+ },
+ "pie",
+ 0,
+ false,
+ "outside",
+ ) as unknown as {
+ series: { center: [string, number | string]; radius: string }[];
+ };
+
+ test("the pie is centred under the title, not at 44%", () => {
+ const { center } = pie({ title: "Revenue share" }).series[0];
+ // 300 px - 40 title - 32 legend = 228; centre 40 + 114.
+ expect(center[1]).toBe(154);
+ });
+
+ test("a short chart shrinks the pie to fit under the title", () => {
+ const tall = pie({ title: "T", chartHeight: 300 }).series[0].radius;
+ const short = pie({ title: "T", chartHeight: 220 }).series[0].radius;
+ expect(parseFloat(short)).toBeLessThan(parseFloat(tall));
+ });
+
+ test("without a title the layout is unchanged", () => {
+ expect(pie().series[0].center).toEqual(["50%", "44%"]);
+ expect(pie().series[0].radius).toBe("70%");
+ });
+});
+
+describe("pie legend keeps the share", () => {
+ const legend = (chartWidth: number) => {
+ const option = buildPieOption(
+ {
+ xData: ["Professional Services and Consulting Partners", "Retail"],
+ yDataMap: { v: [18200, 800] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0"],
+ showLegend: true,
+ v3: true,
+ chartWidth,
+ chartHeight: 260,
+ valueFormatter: (v) => String(v),
+ },
+ "pie",
+ 0,
+ false,
+ "outside",
+ ) as unknown as { legend: { formatter: (name: string) => string } };
+ return option.legend.formatter(
+ "Professional Services and Consulting Partners",
+ );
+ };
+
+ test("a long name is cut and the value and share stay", () => {
+ const text = legend(400);
+ expect(text).toMatch(/\.\.\. 18200 95\.8%$/);
+ expect(text.length).toBeLessThan(55);
+ });
+
+ test("a short name is untouched", () => {
+ const option = buildPieOption(
+ {
+ xData: ["Retail", "Other"],
+ yDataMap: { v: [1, 1] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0"],
+ showLegend: true,
+ v3: true,
+ chartWidth: 900,
+ chartHeight: 400,
+ },
+ "pie",
+ 0,
+ false,
+ "outside",
+ ) as unknown as { legend: { formatter: (name: string) => string } };
+ expect(option.legend.formatter("Retail")).toMatch(/^Retail {2}/);
+ });
+});
+
+describe("pie slice labels", () => {
+ const pie = (v3: boolean, position = "outside") =>
+ buildPieOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [3, 2] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0"],
+ showLegend: false,
+ v3,
+ chartWidth: 400,
+ chartHeight: 320,
+ },
+ "pie",
+ 0,
+ true,
+ position,
+ ) as unknown as {
+ series: {
+ radius: string;
+ label: Record;
+ labelLayout?: unknown;
+ }[];
+ };
+
+ test("v3 outside labels align to the card edges and shrink the pie", () => {
+ const series = pie(true).series[0];
+ expect(series.label).toMatchObject({ alignTo: "edge", edgeDistance: 8 });
+ expect(series.labelLayout).toEqual({ hideOverlap: true });
+ expect(parseFloat(series.radius)).toBeCloseTo(59.5);
+ });
+
+ test("without v3 and for inside labels nothing changes", () => {
+ expect(pie(false).series[0].label.alignTo).toBeUndefined();
+ expect(pie(true, "inside").series[0].label.alignTo).toBeUndefined();
+ expect(pie(true, "inside").series[0].radius).toBe("70%");
+ });
+});
+
+describe("donut centre text", () => {
+ const titleText = (centerLabel: string) => {
+ const option = buildPieOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [3, 2] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0"],
+ showLegend: false,
+ chartWidth: 400,
+ chartHeight: 280,
+ },
+ "donut",
+ undefined,
+ false,
+ "outside",
+ { centerLabel },
+ ) as unknown as {
+ title: { text: string; textStyle: Record }[];
+ };
+ return option.title[0].text;
+ };
+ const lineHeight = () =>
+ (
+ buildPieOption(
+ {
+ xData: ["A", "B"],
+ yDataMap: { v: [3, 2] },
+ yFields: ["v"],
+ colors: ["#f00", "#0f0"],
+ showLegend: false,
+ chartWidth: 400,
+ chartHeight: 280,
+ },
+ "donut",
+ undefined,
+ false,
+ "outside",
+ { centerLabel: "Total revenue across all product lines" },
+ ) as unknown as { title: { textStyle: { lineHeight?: number } }[] }
+ ).title[0].textStyle.lineHeight;
+
+ test("a long text wraps inside the hole and is cut past it", () => {
+ // Box 78 px: 11 characters a line at 11 px, 5 lines of 14 px.
+ const lines = titleText("Total revenue across all product lines").split(
+ "\n",
+ );
+ expect(lines.length).toBeGreaterThan(1);
+ expect(lines.every((l) => l.length <= 11)).toBe(true);
+ expect(lines[0]).toBe("Total");
+ const cut = titleText("word ".repeat(60).trim());
+ expect(cut.endsWith("...")).toBe(true);
+ expect(cut.split("\n")).toHaveLength(5);
+ });
+
+ test("a word longer than a line is cut to the line with one ellipsis", () => {
+ // Box 78 px: 11 characters a line.
+ const [line] = titleText("supercalifragilisticexpialidocious").split("\n");
+ expect(line).toBe("supercal...");
+ });
+
+ test("the last line keeps one ellipsis when the text is cut", () => {
+ const cut = titleText("word ".repeat(60).trim()).split("\n");
+ expect(cut).toHaveLength(5);
+ expect(cut[4]).toBe("word wor...");
+ });
+
+ test("wrapped lines get a line height", () => {
+ expect(lineHeight()).toBe(14);
+ });
+
+ test("a short text keeps its one line", () => {
+ expect(titleText("Total")).toBe("Total");
+ });
+});
+
+describe("radar metric names", () => {
+ test("long names are cut to the name width in the formatter", () => {
+ const name = "Net revenue retention across all enterprise accounts";
+ const option = buildRadarOption({
+ xData: [name, "Short"],
+ yDataMap: { a: [1, 2] },
+ yFields: ["a"],
+ colors: ["#f00"],
+ showLegend: false,
+ chartWidth: 400,
+ chartHeight: 320,
+ }) as unknown as {
+ radar: { axisName: { formatter: (n: string) => string; width: number } };
+ };
+ const { formatter, width } = option.radar.axisName;
+ expect(width).toBe(100);
+ // 100 px / 6.5 = 15 characters, three of them for the ellipsis: 12 kept.
+ expect(formatter(name)).toBe("Net revenue ...");
+ expect(formatter("Short")).toBe("Short");
+ });
+});
+
+describe("radar ring values", () => {
+ const radar = (chartWidth: number, chartHeight: number) =>
+ (
+ buildRadarOption({
+ xData: ["Alpha", "Beta", "Gamma"],
+ yDataMap: { a: [90, 50, 70] },
+ yFields: ["a"],
+ colors: ["#f00"],
+ showLegend: false,
+ chartWidth,
+ chartHeight,
+ }) as unknown as { radar: { splitNumber: number; nameGap: number } }
+ ).radar;
+
+ test("a small radar draws fewer rings", () => {
+ expect(radar(400, 200).splitNumber).toBeLessThan(5);
+ });
+
+ test("a large radar keeps five rings", () => {
+ expect(radar(600, 500).splitNumber).toBe(5);
+ });
+
+ test("metric names sit further out than the top ring value", () => {
+ expect(radar(400, 300).nameGap).toBe(20);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx
new file mode 100644
index 000000000..c4fac9d35
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx
@@ -0,0 +1,220 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { BarChart } from "../bar";
+import { normalizeChartData } from "../normalize";
+import { buildCartesianOption, buildHorizontalBarOption } from "../options";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+const stackCtx = {
+ xData: ["Alpha"],
+ yDataMap: { a: [30], b: [20] },
+ yFields: ["a", "b"],
+ colors: ["#111", "#222"],
+ showLegend: true,
+};
+const items = [
+ {
+ marker: "",
+ seriesName: "A",
+ seriesIndex: 0,
+ value: 30,
+ axisValueLabel: "Alpha",
+ },
+ {
+ marker: "",
+ seriesName: "B",
+ seriesIndex: 1,
+ value: 20,
+ axisValueLabel: "Alpha",
+ },
+];
+type WithTooltip = { tooltip: { formatter: (p: unknown) => string } };
+
+describe("bar labels and tooltips", () => {
+ test("missing and empty categories get distinct labels", () => {
+ const norm = normalizeChartData(
+ [
+ { cat: null, v: 1 },
+ { cat: "", v: 2 },
+ { cat: "A", v: 3 },
+ ],
+ "cat",
+ "v",
+ );
+ expect(norm.xData).toEqual(["(null)", "(empty)", "A"]);
+ });
+
+ test("a stacked bar tooltip totals only the stacked series", () => {
+ const combo = buildCartesianOption({
+ ...stackCtx,
+ seriesConfig: { b: { type: "line", axis: "right" } },
+ chartType: "bar",
+ isTimeSeries: false,
+ stacked: true,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 8,
+ }) as unknown as WithTooltip;
+ const text = combo.tooltip.formatter(items);
+ expect(text).toContain("B: 20");
+ expect(text).toContain("Total: 30");
+ });
+
+ test("a stacked bar tooltip ends with the total", () => {
+ const vertical = buildCartesianOption({
+ ...stackCtx,
+ chartType: "bar",
+ isTimeSeries: false,
+ stacked: true,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 8,
+ }) as unknown as WithTooltip;
+ const text = vertical.tooltip.formatter(items);
+ expect(text).toContain("Total: 50");
+ // Top band (B) first.
+ expect(text.indexOf("B: 20")).toBeLessThan(text.indexOf("A: 30"));
+
+ const horizontal = buildHorizontalBarOption(
+ stackCtx,
+ true,
+ ) as unknown as WithTooltip;
+ expect(horizontal.tooltip.formatter(items)).toContain("Total: 50");
+ });
+
+ test("changing orientation after mount leaves no stale layout", async () => {
+ const rows = [
+ { cat: "A", v: 1 },
+ { cat: "B", v: 2 },
+ ];
+ const { container, rerender } = render(
+ ,
+ );
+ await waitFor(() => expect(chartOption(container)).toBeDefined());
+ rerender(
+ ,
+ );
+ const fresh = render(
+ ,
+ );
+ await waitFor(() => {
+ const a = chartOption<{ grid: unknown[] }>(container);
+ const b = chartOption<{ grid: unknown[] }>(fresh.container);
+ expect(b).toBeDefined();
+ expect(a?.grid).toEqual(b?.grid);
+ });
+ });
+});
+
+describe("line", () => {
+ test("a row with an unparseable date is left out and the rest is sorted", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const norm = normalizeChartData(
+ [
+ { day: "2026-01-03", v: 3 },
+ { day: "TBD", v: 9 },
+ { day: "2026-01-01", v: 1 },
+ { day: "2026-01-02", v: 2 },
+ ],
+ "day",
+ "v",
+ );
+ expect(norm.xAxisType).toBe("time");
+ expect(norm.yDataMap.v).toEqual([1, 2, 3]);
+ expect(norm.rowIndex).toEqual([2, 3, 0]);
+ expect(warn).toHaveBeenCalled();
+ });
+});
+
+describe("area", () => {
+ const areaCtx = {
+ ...stackCtx,
+ chartType: "area" as const,
+ isTimeSeries: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 8,
+ };
+ type AreaOpt = WithTooltip & { series: { areaStyle: { opacity: number } }[] };
+
+ test("a stacked area tooltip lists the top band first and the total", () => {
+ const opt = buildCartesianOption({
+ ...areaCtx,
+ stacked: true,
+ }) as unknown as AreaOpt;
+ const text = opt.tooltip.formatter(items);
+ expect(text.indexOf("B: 20")).toBeLessThan(text.indexOf("A: 30"));
+ expect(text).toContain("Total: 50");
+ });
+
+ test("unstacked overlapping fills are faint", () => {
+ const opt = buildCartesianOption({
+ ...areaCtx,
+ stacked: false,
+ }) as unknown as AreaOpt;
+ expect(opt.series[0].areaStyle.opacity).toBe(0.12);
+ });
+
+ test("a stack that mixes signs warns", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { AreaChart } = await import("../area");
+ render(
+ ,
+ );
+ expect(
+ warn.mock.calls.some(([m]) => String(m).includes("bands cross")),
+ ).toBe(true);
+ });
+});
+
+describe("scatter", () => {
+ test("symbolSize below 2 is drawn at 2 with a warning", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { ScatterChart } = await import("../scatter");
+ const { container } = render(
+ ,
+ );
+ await waitFor(() => {
+ const o = chartOption<{ series: { symbolSize: number }[] }>(container);
+ expect(o?.series[0].symbolSize).toBe(2);
+ });
+ expect(warn).toHaveBeenCalled();
+ });
+
+ test("numeric-string x is numeric even with a date column in the rows", () => {
+ const norm = normalizeChartData(
+ [
+ { x: "30", y: 1, day: "2026-01-01" },
+ { x: "5", y: 4, day: "2026-01-02" },
+ ],
+ "x",
+ "y",
+ undefined,
+ { xType: "value" },
+ );
+ expect(norm.xData).toEqual([5, 30]);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx
new file mode 100644
index 000000000..49d1e2068
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx
@@ -0,0 +1,328 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { buildPieOption } from "../options";
+import { DonutChart, PieChart } from "../pie";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+afterEach(() => cleanup());
+
+type PieOption = {
+ series: {
+ data: { name: string; value: number | null }[];
+ radius: unknown;
+ center: unknown;
+ minAngle?: number;
+ label: { show: boolean };
+ }[];
+ legend?: { formatter?: unknown; type?: string }[];
+ title?: unknown;
+};
+
+async function pieOption(container: HTMLElement) {
+ return waitFor(() => {
+ const option = chartOption(container);
+ expect(option).toBeDefined();
+ return option as PieOption;
+ });
+}
+
+describe("negative values", () => {
+ test("show an error instead of dropping the slice", () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain("negative");
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ });
+});
+
+describe("nothing to draw", () => {
+ test("all-zero data shows the empty state", () => {
+ const { getByText, container } = render(
+ ,
+ );
+ expect(getByText("No data")).toBeTruthy();
+ expect(container.querySelector("canvas")).toBeNull();
+ });
+
+ test("an unknown yKey shows the key error", () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain('yKey "value"');
+ error.mockRestore();
+ });
+
+ test("a normal pie still renders", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect(option.series[0].data).toHaveLength(2);
+ });
+});
+
+const sevenSlices = [
+ { seg: "A", v: 5 },
+ { seg: "B", v: 40 },
+ { seg: "C", v: 10 },
+ { seg: "D", v: 30 },
+ { seg: "E", v: 3 },
+ { seg: "F", v: 2 },
+ { seg: "G", v: 10 },
+];
+
+describe("v3 pie defaults", () => {
+ test("largest first, the tail as Other, labels off, legend with share", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ const series = option.series[0];
+ expect(series.data.map((d) => d.name)).toEqual([
+ "B",
+ "D",
+ "C",
+ "G",
+ "Other",
+ ]);
+ expect(series.data[4].value).toBe(10);
+ expect(series.label.show).toBe(false);
+ expect(series.center).toEqual(["50%", "44%"]);
+ const formatter = option.legend?.[0].formatter as (name: string) => string;
+ expect(formatter("B")).toBe("B 40 40%");
+ });
+
+ test("a v3 donut shows the total in the hole", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ const titles = option.title as { text: string }[];
+ expect(titles.map((t) => t.text)).toContain("100");
+ });
+
+ test("without v3 nothing changes", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect(option.series[0].data.map((d) => d.name)).toEqual(
+ sevenSlices.map((r) => r.seg),
+ );
+ expect(option.series[0].label.show).toBe(true);
+ });
+});
+
+describe("small and zero slices", () => {
+ test("zero and null slices are not drawn; tiny slices keep their true size", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect(option.series[0].data.map((d) => d.name)).toEqual(["Ok", "Failed"]);
+ expect(option.series[0].minAngle ?? 0).toBe(0);
+ });
+});
+
+describe("hole radius", () => {
+ test("is clamped to 90% of the outer radius", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect(option.series[0].radius).toEqual(["63%", "70%"]);
+ });
+
+ test("0 on a DonutChart draws a pie, unset gives 40", async () => {
+ const zero = render(
+ ,
+ );
+ expect((await pieOption(zero.container)).series[0].radius).toBe("70%");
+ cleanup();
+ const unset = render();
+ expect((await pieOption(unset.container)).series[0].radius).toEqual([
+ "40%",
+ "70%",
+ ]);
+ });
+});
+
+describe("legend layout", () => {
+ const ctx = (over: Record) => ({
+ xData: ["Critical - customer facing outage", "Low"],
+ yDataMap: { v: [3, 7] },
+ yFields: ["v"],
+ colors: ["#111", "#222"],
+ showLegend: true,
+ ...over,
+ });
+ type Built = {
+ legend: { orient: string; textStyle: { width: number; overflow: string } };
+ series: { center: string[] }[];
+ };
+
+ test("a wide chart gets a width-limited side legend and the pie centred in the rest", () => {
+ const opt = buildPieOption(
+ ctx({ chartWidth: 600, chartHeight: 300 }),
+ "donut",
+ undefined,
+ false,
+ "outside",
+ ) as unknown as Built;
+ expect(opt.legend.orient).toBe("vertical");
+ expect(opt.legend.textStyle).toMatchObject({
+ width: 150,
+ overflow: "truncate",
+ });
+ expect(opt.series[0].center).toEqual(["65%", "50%"]);
+ });
+
+ test("a narrow chart puts the legend underneath", () => {
+ const opt = buildPieOption(
+ ctx({ chartWidth: 240, chartHeight: 240 }),
+ "pie",
+ undefined,
+ false,
+ "outside",
+ ) as unknown as Built;
+ expect(opt.legend.orient).toBe("horizontal");
+ expect(opt.series[0].center).toEqual(["50%", "44%"]);
+ });
+
+ test("without a legend the pie is centred", () => {
+ const opt = buildPieOption(
+ ctx({ showLegend: false, chartWidth: 480 }),
+ "donut",
+ undefined,
+ false,
+ "outside",
+ ) as unknown as Built;
+ expect(opt.series[0].center).toEqual(["50%", "50%"]);
+ });
+});
+
+describe("donut hole text", () => {
+ const big = [
+ { seg: "A", v: 5_000_000 },
+ { seg: "B", v: 4_700_000 },
+ ];
+ test("a total that does not fit the hole is compacted", () => {
+ const opt = buildPieOption(
+ {
+ xData: big.map((r) => r.seg),
+ yDataMap: { v: big.map((r) => r.v) },
+ yFields: ["v"],
+ colors: ["#111"],
+ showLegend: false,
+ chartWidth: 120,
+ chartHeight: 120,
+ },
+ "donut",
+ undefined,
+ false,
+ "outside",
+ { centerLabel: true },
+ ) as unknown as {
+ title: { text: string; textStyle: { fontSize: number } }[];
+ };
+ expect(opt.title[0].text).toBe("9.7M");
+ expect(opt.title[0].textStyle.fontSize).toBeGreaterThanOrEqual(11);
+ });
+
+ test("centerLabel text is shown on a DonutChart", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect((option.title as { text: string }[]).map((t) => t.text)).toContain(
+ "Tickets",
+ );
+ });
+});
+
+describe("pie", () => {
+ test("null and empty names are labelled, duplicates and extra yKeys warn", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { container } = render(
+ ,
+ );
+ const option = await pieOption(container);
+ expect(option.series[0].data.map((d) => d.name)).toEqual([
+ "(null)",
+ "(empty)",
+ "Dup",
+ "Dup",
+ ]);
+ expect(
+ warn.mock.calls.some(([m]) => String(m).includes("first yKey")),
+ ).toBe(true);
+ warn.mockRestore();
+ });
+
+ test("inside labels contrast; legend clicks don't rescale", () => {
+ const opt = buildPieOption(
+ {
+ xData: ["a", "b"],
+ yDataMap: { v: [1, 2] },
+ yFields: ["v"],
+ colors: ["#111"],
+ showLegend: true,
+ },
+ "pie",
+ undefined,
+ true,
+ "inside",
+ ) as unknown as {
+ legend: { selectedMode: boolean };
+ series: { label: { color: string } }[];
+ };
+ expect(opt.series[0].label.color).toBe("#fff");
+ expect(opt.legend.selectedMode).toBe(false);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx
new file mode 100644
index 000000000..84d05a983
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx
@@ -0,0 +1,216 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+
+import { buildRadarOption } from "../options";
+import { RadarChart } from "../radar";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+type RadarOption = {
+ radar: {
+ indicator: { name: string; max: number; axisLabel?: { show: boolean } }[];
+ }[];
+ series: { data: { name: string; value: (number | null)[] }[] }[];
+};
+
+async function radarOption(container: HTMLElement) {
+ return waitFor(() => {
+ const option = chartOption(container);
+ expect(option).toBeDefined();
+ return option as RadarOption;
+ });
+}
+
+const scores = [
+ { metric: "speed", a: 72 },
+ { metric: "power", a: 64 },
+ { metric: "range", a: 91 },
+];
+
+describe("rim value", () => {
+ test("max sets the rim and the first spoke shows ring values", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await radarOption(container);
+ const indicator = option.radar[0].indicator;
+ expect(indicator.map((i) => i.max)).toEqual([100, 100, 100]);
+ expect(indicator[0].axisLabel?.show).toBe(true);
+ expect(indicator[1].axisLabel).toBeUndefined();
+ });
+
+ test("max per metric", () => {
+ const opt = buildRadarOption(
+ {
+ xData: ["a", "b"],
+ yDataMap: { v: [1, 2] },
+ yFields: ["v"],
+ colors: ["#111"],
+ showLegend: false,
+ },
+ true,
+ [10, 5],
+ ) as unknown as RadarOption & { radar: RadarOption["radar"][number] };
+ expect(opt.radar.indicator.map((i) => i.max)).toEqual([10, 5]);
+ });
+});
+
+describe("values a radar can't draw", () => {
+ test("negative values show an error", () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain("negative");
+ });
+
+ test("all zeros show the empty state", () => {
+ const { getByText } = render(
+ ,
+ );
+ expect(getByText("No data")).toBeTruthy();
+ });
+});
+
+describe("one row per entity", () => {
+ test("metrics turns entity rows into spokes and polygons", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await radarOption(container);
+ expect(option.radar[0].indicator.map((i) => i.name)).toEqual([
+ "speed",
+ "power",
+ "range",
+ ]);
+ expect(option.series[0].data.map((d) => d.name)).toEqual(["Red", "Blue"]);
+ expect(option.series[0].data[1].value).toEqual([40, 80, 60]);
+ });
+
+ test("an unknown metric is reported", () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const { getByRole } = render(
+ ,
+ );
+ expect(getByRole("alert").textContent).toContain('metrics "power"');
+ });
+});
+
+describe("narrow radar", () => {
+ test("names are truncated to their space and the radius fills the rest", () => {
+ const opt = buildRadarOption(
+ {
+ xData: [
+ "Customer satisfaction score",
+ "Net revenue retention",
+ "Uptime",
+ ],
+ yDataMap: { v: [1, 2, 3] },
+ yFields: ["v"],
+ colors: ["#111"],
+ showLegend: false,
+ chartWidth: 280,
+ chartHeight: 240,
+ },
+ true,
+ ) as unknown as {
+ radar: { radius: number; axisName: { width: number; overflow: string } };
+ };
+ expect(opt.radar.axisName).toMatchObject({
+ width: 70,
+ overflow: "truncate",
+ });
+ expect(opt.radar.radius).toBe(58);
+ });
+});
+
+describe("dark theme", () => {
+ test("ring bands use the theme grid color", () => {
+ const grid = "hsla(240, 4%, 20%, 1)";
+ const opt = buildRadarOption(
+ {
+ xData: ["a", "b", "c"],
+ yDataMap: { v: [1, 2, 3] },
+ yFields: ["v"],
+ colors: ["#111"],
+ showLegend: false,
+ ui: {
+ axisLabel: "#aaa",
+ axisTitle: "#eee",
+ grid,
+ tooltipBg: "#000",
+ },
+ },
+ true,
+ ) as unknown as {
+ radar: { splitArea: { areaStyle: { color: string[] } } };
+ };
+ expect(opt.radar.splitArea.areaStyle.color).toEqual([grid, "transparent"]);
+ });
+});
+
+describe("radar", () => {
+ test("a polygon keeps its color when another series is removed", async () => {
+ const rows = [
+ { metric: "a", x: 1, y: 2 },
+ { metric: "b", x: 3, y: 4 },
+ ];
+ const colors = ["#111111", "#222222", "#333333"];
+ const { container, rerender } = render(
+ ,
+ );
+ const colorOf = async (name: string) =>
+ waitFor(() => {
+ const o = chartOption<{
+ series: { data: { name: string; itemStyle: { color: string } }[] }[];
+ }>(container);
+ const item = o?.series[0].data.find((d) => d.name === name);
+ expect(item).toBeDefined();
+ return item?.itemStyle.color;
+ });
+ expect(await colorOf("Y")).toBe("#222222");
+ rerender(
+ ,
+ );
+ await waitFor(async () => {
+ const o = chartOption<{ series: { data: unknown[] }[] }>(container);
+ expect(o?.series[0].data).toHaveLength(1);
+ });
+ expect(await colorOf("Y")).toBe("#222222");
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx
index c99f86454..4632a04a2 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx
+++ b/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx
@@ -42,3 +42,97 @@ describe("ChartWrapper sizing", () => {
expect(box.style.minHeight).toBe("");
});
});
+
+describe("className heights and v3 default height", () => {
+ test("a className height leaves no inline height to override it", () => {
+ render(
+
+ {() => chart}
+ ,
+ );
+ const box = screen.getByTestId("w");
+ expect(box.style.height).toBe("");
+ expect(box.style.minHeight).not.toBe("");
+ });
+
+ test.each([
+ "md:h-96",
+ "size-80",
+ "rounded h-[18rem] p-2",
+ "h-full",
+ "h-auto",
+ ])(
+ "%s is a className height: no inline height, but the minimum stays",
+ (className) => {
+ expect(chartSizeStyle(undefined, { className })).toEqual({
+ minHeight: CHART_MIN_HEIGHT,
+ });
+ },
+ );
+
+ test.each(["min-h-[200px]", "max-h-96", "rounded p-2"])(
+ "%s does not",
+ (className) => {
+ expect(chartSizeStyle(undefined, { className })).toEqual({
+ height: "100%",
+ minHeight: CHART_MIN_HEIGHT,
+ });
+ },
+ );
+
+ test("v3 takes 300 px when the parent has no height", () => {
+ render(
+
+ {() => chart}
+ ,
+ );
+ const box = screen.getByTestId("w");
+ expect(box.style.height).toBe("100%");
+ expect(box.style.minHeight).toBe("300px");
+ });
+
+ test("an explicit height still wins with v3", () => {
+ expect(chartSizeStyle(208, { defaults: "v3" })).toEqual({ height: 208 });
+ });
+});
+
+describe("states keep the chart box", () => {
+ test("an empty result keeps the height", () => {
+ render(
+
+ {() => chart}
+ ,
+ );
+ const box = screen.getByTestId("w");
+ expect(box.style.height).toBe("300px");
+ expect(box.textContent).toContain("No data available");
+ });
+
+ test("data mode shows loading in the chart box", () => {
+ render(
+
+ {() => chart}
+ ,
+ );
+ const box = screen.getByTestId("w");
+ expect(box.style.height).toBe("300px");
+ expect(box.textContent).not.toContain("No data available");
+ expect(box.querySelector(".animate-pulse")).not.toBeNull();
+ });
+
+ test("data mode shows an error in the chart box", () => {
+ render(
+
+ {() => chart}
+ ,
+ );
+ const box = screen.getByTestId("w");
+ expect(box.style.height).toBe("240px");
+ expect(box.textContent).toContain("warehouse is down");
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/sparkline.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/sparkline.test.tsx
new file mode 100644
index 000000000..583b0e077
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/sparkline.test.tsx
@@ -0,0 +1,78 @@
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test } from "vitest";
+
+import { AreaChart } from "../area";
+import { LineChart } from "../line";
+import { chartOption, installEChartsEnv } from "./helpers/echarts-env";
+
+beforeAll(() => installEChartsEnv());
+afterEach(() => cleanup());
+
+type SparkOption = {
+ xAxis: { show: boolean }[];
+ yAxis: { show: boolean; scale: boolean }[];
+ legend?: unknown[];
+ grid: { left: number }[];
+ series: { data: unknown[]; showSymbol?: boolean }[];
+};
+
+async function sparkOption(container: HTMLElement) {
+ return waitFor(() => {
+ const o = chartOption(container);
+ expect(o).toBeDefined();
+ return o as SparkOption;
+ });
+}
+
+describe("sparkline", () => {
+ test("no axes or legend, fitted y range, 48 px tall", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await sparkOption(container);
+ expect(option.xAxis[0].show).toBe(false);
+ expect(option.yAxis[0]).toMatchObject({ show: false, scale: true });
+ expect(option.legend ?? []).toHaveLength(0);
+ expect(option.grid[0].left).toBe(2);
+ const box = container.querySelector("[role=img]");
+ expect(box?.style.height).toBe("48px");
+ });
+
+ test("a missing day is a gap, not a drop to 0", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await sparkOption(container);
+ expect(option.series[0].data[1]).toBeNull();
+ });
+
+ test("one point is visible", async () => {
+ const { container } = render(
+ ,
+ );
+ const option = await sparkOption(container);
+ expect(option.series[0].showSymbol).toBe(true);
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/theme.test.ts b/packages/appkit-ui/src/react/charts/__tests__/theme.test.ts
index 6e79eacda..bda732821 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/theme.test.ts
+++ b/packages/appkit-ui/src/react/charts/__tests__/theme.test.ts
@@ -15,6 +15,7 @@ import {
resetThemeCache,
useAllThemeColors,
useChartUITokens,
+ useResolvedColors,
useThemeColors,
} from "../theme";
import type { ChartColorPalette } from "../types";
@@ -827,3 +828,33 @@ describe("shared theme-change subscription", () => {
expect(disconnectSpy).toHaveBeenCalledTimes(1);
});
});
+
+describe("useResolvedColors", () => {
+ const originalMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ resetThemeCache();
+ window.matchMedia = createMockMatchMedia() as typeof window.matchMedia;
+ });
+ afterEach(() => {
+ resetThemeCache();
+ window.matchMedia = originalMatchMedia;
+ });
+
+ test("resolves var() tokens against the root element", () => {
+ document.documentElement.style.setProperty("--chart-cat-1", "#123456");
+ const { result } = renderHook(() =>
+ useResolvedColors([
+ "var(--chart-cat-1)",
+ "#abcdef",
+ "var(--missing, #00ff00)",
+ ]),
+ );
+ expect(result.current).toEqual(["#123456", "#abcdef", "#00ff00"]);
+ document.documentElement.style.removeProperty("--chart-cat-1");
+ });
+
+ test("undefined stays undefined", () => {
+ const { result } = renderHook(() => useResolvedColors(undefined));
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts
new file mode 100644
index 000000000..21c7392eb
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts
@@ -0,0 +1,147 @@
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import { normalizeChartData } from "../normalize";
+import { buildCartesianOption, buildHorizontalBarOption } from "../options";
+import { formatLocalDate, toChronologicalValue } from "../utils";
+
+// Run as a viewer west of UTC, where a UTC-midnight DATE is the previous day.
+const originalTz = process.env.TZ;
+beforeAll(() => {
+ process.env.TZ = "America/Los_Angeles";
+});
+afterAll(() => {
+ process.env.TZ = originalTz;
+});
+
+describe("DATE strings west of UTC", () => {
+ test("a DATE is the same calendar day for the viewer", () => {
+ const ts = toChronologicalValue("2026-01-01");
+ expect(ts).not.toBeNull();
+ const d = new Date(ts as number);
+ expect([d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()]).toEqual([
+ 2026, 0, 1, 0,
+ ]);
+ expect(formatLocalDate(ts as number)).toBe("2026-01-01");
+ });
+
+ test("an impossible DATE is not a date", () => {
+ expect(toChronologicalValue("2026-02-31")).toBeNull();
+ });
+
+ test("date-only data shows the tooltip header without a time", () => {
+ const n = normalizeChartData(
+ [
+ { day: "2026-01-01", v: 1 },
+ { day: "2026-01-02", v: 2 },
+ ],
+ "day",
+ "v",
+ );
+ expect(n.xDateOnly).toBe(true);
+ const opt = buildCartesianOption({
+ ...n,
+ colors: ["#000"],
+ showLegend: false,
+ chartType: "line",
+ isTimeSeries: true,
+ xDateOnly: n.xDateOnly,
+ stacked: false,
+ smooth: false,
+ showSymbol: false,
+ symbolSize: 4,
+ }) as {
+ xAxis: {
+ axisPointer?: {
+ label: { formatter: (p: { value: number }) => string };
+ };
+ };
+ };
+ const header = opt.xAxis.axisPointer?.label.formatter({
+ value: n.xData[0] as number,
+ });
+ expect(header).toBe("2026-01-01");
+ });
+});
+
+describe("one timezone rule", () => {
+ test("a DATE and a zone-less DATE_TRUNC timestamp of the same day agree", () => {
+ expect(toChronologicalValue("2026-01-01 00:00:00")).toBe(
+ toChronologicalValue("2026-01-01"),
+ );
+ expect(toChronologicalValue("2026-01-01T00:00:00.000000")).toBe(
+ toChronologicalValue("2026-01-01"),
+ );
+ });
+
+ test("a zone-less timestamp is a wall-clock time", () => {
+ const d = new Date(
+ toChronologicalValue("2026-03-05 14:30:15.250") as number,
+ );
+ expect([
+ d.getHours(),
+ d.getMinutes(),
+ d.getSeconds(),
+ d.getMilliseconds(),
+ ]).toEqual([14, 30, 15, 250]);
+ });
+
+ test("a timestamp with Z or an offset stays an absolute instant", () => {
+ expect(toChronologicalValue("2026-01-01T00:00:00Z")).toBe(
+ Date.UTC(2026, 0, 1),
+ );
+ expect(toChronologicalValue("2026-01-01T00:00:00+02:00")).toBe(
+ Date.UTC(2025, 11, 31, 22),
+ );
+ });
+});
+
+describe("dates on category axes", () => {
+ test("JS Date objects are time values, not category strings", () => {
+ const n = normalizeChartData(
+ [
+ { day: new Date(2026, 0, 2), v: 2 },
+ { day: new Date(2026, 0, 1), v: 1 },
+ ],
+ "day",
+ "v",
+ );
+ expect(n.chartType).toBe("timeseries");
+ expect(n.xData).toEqual([
+ new Date(2026, 0, 1).getTime(),
+ new Date(2026, 0, 2).getTime(),
+ ]);
+ });
+
+ test("horizontal bars with a date xKey label dates, not epoch milliseconds", () => {
+ const n = normalizeChartData(
+ [
+ { day: "2026-01-01", v: 1 },
+ { day: "2026-01-02", v: 2 },
+ ],
+ "day",
+ "v",
+ "horizontal",
+ );
+ const opt = buildHorizontalBarOption(
+ {
+ ...n,
+ colors: ["#000"],
+ showLegend: false,
+ xIsTime: n.chartType === "timeseries",
+ xDateOnly: n.xDateOnly,
+ },
+ false,
+ ) as {
+ yAxis: {
+ axisLabel: { formatter: (v: string) => string };
+ axisPointer: { label: { formatter: (p: { value: number }) => string } };
+ };
+ };
+ expect(opt.yAxis.axisLabel.formatter(String(n.xData[0]))).toBe(
+ "2026-01-01",
+ );
+ expect(
+ opt.yAxis.axisPointer.label.formatter({ value: n.xData[1] as number }),
+ ).toBe("2026-01-02");
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/types.test.ts b/packages/appkit-ui/src/react/charts/__tests__/types.test.ts
index b317110af..5e989f56d 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/types.test.ts
+++ b/packages/appkit-ui/src/react/charts/__tests__/types.test.ts
@@ -1,6 +1,13 @@
-import { describe, expect, test } from "vitest";
+import { describe, expect, expectTypeOf, test } from "vitest";
-import { isArrowTable, isDataProps, isQueryProps } from "../types";
+import {
+ type AreaChartSpecificProps,
+ type BarChartSpecificProps,
+ isArrowTable,
+ isDataProps,
+ isQueryProps,
+ type LineChartSpecificProps,
+} from "../types";
describe("isArrowTable", () => {
test("returns true for Arrow-like objects", () => {
@@ -229,3 +236,11 @@ describe("type discrimination", () => {
expect(isDataProps(invalidProps as any)).toBe(true);
});
});
+
+describe("orientation is bar-only", () => {
+ test("LineChart and AreaChart props have no orientation", () => {
+ expectTypeOf().not.toHaveProperty("orientation");
+ expectTypeOf().not.toHaveProperty("orientation");
+ expectTypeOf().toHaveProperty("orientation");
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/__tests__/utils.test.ts b/packages/appkit-ui/src/react/charts/__tests__/utils.test.ts
index 26518524c..468e10552 100644
--- a/packages/appkit-ui/src/react/charts/__tests__/utils.test.ts
+++ b/packages/appkit-ui/src/react/charts/__tests__/utils.test.ts
@@ -3,6 +3,9 @@ import { describe, expect, test } from "vitest";
import {
createTimeSeriesData,
escapeHtml,
+ formatCompactNumber,
+ formatFullNumber,
+ formatLabelNumber,
formatLabel,
mapToDatum,
sortTimeSeriesAscending,
@@ -605,3 +608,51 @@ describe("mapToDatum", () => {
});
});
});
+
+describe("compact ticks keep small values", () => {
+ test("a value under 0.05 is not rounded to 0", () => {
+ expect(formatCompactNumber(0.012)).toBe("0.012");
+ expect(formatCompactNumber(0.04)).toBe("0.04");
+ expect(formatCompactNumber(-0.003)).toBe("-0.003");
+ });
+
+ test("zero and larger numbers keep the compact format", () => {
+ expect(formatCompactNumber(0)).toBe("0");
+ expect(formatCompactNumber(18234567)).toBe("18.2M");
+ expect(formatCompactNumber(2500)).toBe("2.5K");
+ expect(formatCompactNumber(1)).toBe("1");
+ });
+
+ test("a non-number is returned as it is", () => {
+ expect(formatCompactNumber("n/a")).toBe("n/a");
+ });
+});
+
+describe("full tooltip values keep their digits", () => {
+ test("small values keep three significant digits", () => {
+ expect(formatFullNumber(0.012)).toBe("0.012");
+ expect(formatFullNumber(0.018)).toBe("0.018");
+ expect(formatFullNumber(0.123456)).toBe("0.123");
+ });
+
+ test("grouped values keep their decimals", () => {
+ expect(formatFullNumber(15234567.89)).toBe("15,234,567.89");
+ expect(formatFullNumber(0)).toBe("0");
+ expect(formatFullNumber("n/a")).toBe("n/a");
+ });
+});
+
+describe("value labels keep three significant digits", () => {
+ test("neighbouring values read differently", () => {
+ expect(formatLabelNumber(1249000)).toBe("1.25M");
+ expect(formatLabelNumber(1250000)).toBe("1.25M");
+ expect(formatLabelNumber(1349999)).toBe("1.35M");
+ expect(formatLabelNumber(82812)).toBe("82.8K");
+ });
+
+ test("quarters and small values are not rounded to one decimal", () => {
+ expect(formatLabelNumber(0.25)).toBe("0.25");
+ expect(formatLabelNumber(0.012)).toBe("0.012");
+ expect(formatLabelNumber(-999999)).toBe("-1M");
+ });
+});
diff --git a/packages/appkit-ui/src/react/charts/area/examples/area.example.tsx b/packages/appkit-ui/src/react/charts/area/examples/area.example.tsx
index 162cf34fb..ad62a6434 100644
--- a/packages/appkit-ui/src/react/charts/area/examples/area.example.tsx
+++ b/packages/appkit-ui/src/react/charts/area/examples/area.example.tsx
@@ -1,22 +1,37 @@
-"use client";
-
import { AreaChart } from "@databricks/appkit-ui/react";
+// Long rows as `config/queries/revenue_by_channel.sql` returns them, one row
+// per month and channel; `seriesKey` turns each channel into a stacked band.
+// SELECT DATE_TRUNC('MONTH', order_date) AS month, channel,
+// CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY 1, 2 ORDER BY 1
+const rows = [
+ { month: "2026-01-01", channel: "Online", revenue: 412000 },
+ { month: "2026-01-01", channel: "Retail", revenue: 268000 },
+ { month: "2026-02-01", channel: "Online", revenue: 451000 },
+ { month: "2026-02-01", channel: "Retail", revenue: 259000 },
+ { month: "2026-03-01", channel: "Online", revenue: 498000 },
+ { month: "2026-03-01", channel: "Retail", revenue: 281000 },
+ { month: "2026-04-01", channel: "Online", revenue: 530000 },
+ { month: "2026-04-01", channel: "Retail", revenue: 274000 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
+
export default function AreaChartExample() {
return (
);
diff --git a/packages/appkit-ui/src/react/charts/area/index.tsx b/packages/appkit-ui/src/react/charts/area/index.tsx
index 61512675b..86a4bfaac 100644
--- a/packages/appkit-ui/src/react/charts/area/index.tsx
+++ b/packages/appkit-ui/src/react/charts/area/index.tsx
@@ -4,10 +4,18 @@ import type { AreaChartProps } from "../types";
/**
* Area Chart component for trend visualization with filled areas.
*
- * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+ * **Use when:** the split of a total changes over time (stacked), or for a running total.
+ *
+ * **Not when:** up to 12 periods (stacked BarChart); over 5 parts (top 4 plus "Other" in SQL); values of mixed sign.
+ *
+ * **Rows:** one per period and part: long rows plus `seriesKey`, or one column per part.
*
- * **Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+ * **Gotchas:** pass `stacked` for composition; unstacked areas overlap. A stack of mixed-sign values logs a warning.
+ *
+ * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
*
- * Supports both query mode (queryKey + parameters) and data mode (static data).
+ * **Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+ * elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+ * the UI is built first; add `loading` and `error` so the chart shows those states in its box.
*/
export const AreaChart = createChart("area", "AreaChart");
diff --git a/packages/appkit-ui/src/react/charts/bar/examples/bar.example.tsx b/packages/appkit-ui/src/react/charts/bar/examples/bar.example.tsx
index 7af68fbe8..780325f42 100644
--- a/packages/appkit-ui/src/react/charts/bar/examples/bar.example.tsx
+++ b/packages/appkit-ui/src/react/charts/bar/examples/bar.example.tsx
@@ -1,19 +1,32 @@
-"use client";
-
import { BarChart } from "@databricks/appkit-ui/react";
+// Rows as `config/queries/revenue_by_segment.sql` returns them:
+// SELECT segment, CAST(SUM(amount) AS DOUBLE) AS revenue
+// FROM orders GROUP BY segment ORDER BY revenue DESC LIMIT 10
+// In an app, pass the query instead of the rows:
+//
+const rows = [
+ { segment: "Enterprise", revenue: 1840500 },
+ { segment: "Mid-market", revenue: 1215300 },
+ { segment: "SMB", revenue: 864200 },
+ { segment: "Public sector", revenue: 512900 },
+ { segment: "Education", revenue: 301750 },
+];
+
+const usd = (value: string | number) =>
+ new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ notation: "compact",
+ }).format(Number(value));
+
export default function BarChartExample() {
return (
);
diff --git a/packages/appkit-ui/src/react/charts/bar/index.tsx b/packages/appkit-ui/src/react/charts/bar/index.tsx
index 67fbd6a34..503434fdb 100644
--- a/packages/appkit-ui/src/react/charts/bar/index.tsx
+++ b/packages/appkit-ui/src/react/charts/bar/index.tsx
@@ -4,10 +4,18 @@ import type { BarChartProps } from "../types";
/**
* Bar Chart component for categorical comparisons.
*
- * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+ * **Use when:** comparing one measure across 3 to 15 categories, or across up to 12 periods.
+ *
+ * **Not when:** more than 15 categories (DataTable); more than 12 periods (LineChart); 2 to 5 parts of one whole (DonutChart); one category (a KPI tile).
+ *
+ * **Rows:** one per category, already sorted in SQL; a category column (text) and a measure column (number). Several series: one measure column each, or long rows plus `seriesKey`.
*
- * **Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+ * **Gotchas:** categories keep their row order, numbers and years included (`xType="value"` sorts them). Pass `orientation` if the automatic rule picks the wrong one. Cast DECIMAL to DOUBLE in SQL, or pass the strings: both parse.
+ *
+ * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
*
- * Supports both query mode (queryKey + parameters) and data mode (static data).
+ * **Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+ * elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+ * the UI is built first; add `loading` and `error` so the chart shows those states in its box.
*/
export const BarChart = createChart("bar", "BarChart");
diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx
index 28b1ca831..65f8605a6 100644
--- a/packages/appkit-ui/src/react/charts/base.tsx
+++ b/packages/appkit-ui/src/react/charts/base.tsx
@@ -1,6 +1,6 @@
// Type-only import: erased at compile time, does not pull the full echarts
// bundle in. The `ECharts` type is used for the stored ECharts instance ref.
-import type { ECharts } from "echarts";
+import type { ECharts, EChartsOption } from "echarts";
// Import the ESM core build, not `echarts-for-react/lib/core` (CJS). The package
// has no `exports` map, so `/lib/core` resolves to the literal CommonJS file
// whose default export is `module.exports`; under ESM default-import interop a
@@ -17,8 +17,10 @@ import {
ScatterChart,
} from "echarts/charts";
import {
+ DataZoomComponent,
GridComponent,
LegendComponent,
+ MarkLineComponent,
TitleComponent,
TooltipComponent,
VisualMapComponent,
@@ -26,10 +28,18 @@ import {
import * as echarts from "echarts/core";
import { LegacyGridContainLabel } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
-import { useCallback, useMemo, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { type ClickContext, resolveClickDatum } from "./click";
import { chartSizeStyle } from "./constants";
-import { normalizeChartData, normalizeHeatmapData } from "./normalize";
+import {
+ normalizeChartData,
+ normalizeHeatmapData,
+ NULL_X_LABEL,
+ pivotRadarEntities,
+ RADAR_METRIC_KEY,
+ unknownKeysMessage,
+} from "./normalize";
import {
applySelectionEmphasis,
buildCartesianOption,
@@ -37,19 +47,30 @@ import {
buildHorizontalBarOption,
buildPieOption,
buildRadarOption,
+ type ChartOptionsInput,
+ mergeChartOptions,
type OptionBuilderContext,
} from "./options";
-import { useChartUITokens, useThemeColors } from "./theme";
+import { useChartUITokens, useResolvedColors, useThemeColors } from "./theme";
import type {
- ChartBaseProps,
ChartClickDatum,
ChartColorPalette,
ChartData,
+ ChartDefaults,
+ ChartReferenceLine,
+ ChartSeriesConfig,
ChartType,
ChartValueFormatter,
Orientation,
+ XAxisType,
} from "./types";
-import { mapToDatum } from "./utils";
+import {
+ formatCompactNumber,
+ formatFullNumber,
+ formatLabelNumber,
+ formatLabel,
+ mapToDatum,
+} from "./utils";
// ============================================================================
// ECharts Registration (modular imports for tree-shaking)
@@ -59,8 +80,8 @@ import { mapToDatum } from "./utils";
// full `echarts` entry keeps unused chart types (graph, sankey, gauge, ...)
// out of consumer bundles.
//
-// If you add a new chart type or use a new ECharts feature (e.g. dataZoom,
-// toolbox, markLine), register it here. Consumers passing custom `options`
+// If you add a new chart type or use a new ECharts feature (e.g. toolbox,
+// markArea), register it here. Consumers passing custom `options`
// that need extra features can register them in their own app via
// `import { use } from "echarts/core"`.
//
@@ -85,6 +106,8 @@ echarts.use([
LegendComponent, // `legend`
GridComponent, // `grid` / `xAxis` / `yAxis`
VisualMapComponent, // `visualMap` (heatmap color scale)
+ MarkLineComponent, // `markLine` (referenceLines)
+ DataZoomComponent, // `dataZoom` inside + slider (zoom)
// Features
LegacyGridContainLabel, // `grid.containLabel` (cartesian option builder)
// Renderer (BaseChart always renders with `renderer: "canvas"`)
@@ -109,6 +132,217 @@ function getDefaultPalette(chartType: ChartType): ChartColorPalette {
}
}
+// ============================================================================
+// Data Checks
+// ============================================================================
+
+/**
+ * A scatter x axis is numeric (or time): text x values draw nothing. Returns
+ * the message to show, or null when at least one x value is a number.
+ */
+function scatterXError(normalized: {
+ xData: (string | number)[];
+ xField: string;
+}): string | null {
+ const values = normalized.xData.filter((x) => x !== "" && x !== NULL_X_LABEL);
+ if (values.length === 0) return null;
+ const numeric = values.some(
+ (x) =>
+ typeof x === "number" || (x.trim() !== "" && Number.isFinite(Number(x))),
+ );
+ if (numeric) return null;
+ return `xKey "${normalized.xField}" holds text (such as ${JSON.stringify(values[0])}). A scatter chart needs numbers or dates on x; use a BarChart for categories.`;
+}
+
+/** Size and radar layout of a chart instance, for radar click hit-testing. */
+function radarGeometry(instance: ECharts) {
+ try {
+ const option = instance.getOption() as {
+ radar?: {
+ center?: [string | number, string | number];
+ startAngle?: number;
+ clockwise?: boolean;
+ }[];
+ };
+ const radar = option.radar?.[0];
+ return {
+ width: instance.getWidth(),
+ height: instance.getHeight(),
+ center: radar?.center,
+ startAngle: radar?.startAngle,
+ clockwise: radar?.clockwise,
+ };
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * A pie can't show a negative part of a whole: it used to drop the slice from
+ * the ring, keep it in the legend and compute shares over the positive values.
+ */
+function pieValueError(normalized: {
+ yFields: string[];
+ yDataMap?: Record;
+}): string | null {
+ const field = normalized.yFields[0];
+ const values = field ? (normalized.yDataMap?.[field] ?? []) : [];
+ const negative = values.find((v) => v !== null && Number(v) < 0);
+ if (negative === undefined) return null;
+ return `yKey "${field}" has negative values (such as ${negative}). A pie shows parts of a whole; use a BarChart for values that can be negative.`;
+}
+
+/** True when a pie has nothing to draw: every value is 0, null or missing. */
+function pieIsEmpty(normalized: {
+ yFields: string[];
+ yDataMap?: Record;
+}): boolean {
+ const field = normalized.yFields[0];
+ const values = field ? (normalized.yDataMap?.[field] ?? []) : [];
+ return !values.some((v) => v !== null && Number(v) > 0);
+}
+
+/**
+ * A radar is drawn from the centre out: negative values give a negative rim
+ * and a meaningless shape.
+ */
+function radarValueError(normalized: {
+ yFields: string[];
+ yDataMap?: Record;
+}): string | null {
+ for (const field of normalized.yFields) {
+ const negative = normalized.yDataMap?.[field]?.find(
+ (v) => v !== null && Number(v) < 0,
+ );
+ if (negative !== undefined) {
+ return `yKey "${field}" has negative values (such as ${negative}). A radar plots values from the centre out; shift or normalise the metrics to 0 or more, or use a BarChart.`;
+ }
+ }
+ return null;
+}
+
+/** True when no series has a value above 0 (a radar of zeros is a dot). */
+function allZero(normalized: {
+ yFields: string[];
+ yDataMap?: Record;
+}): boolean {
+ return !normalized.yFields.some((field) =>
+ normalized.yDataMap?.[field]?.some((v) => v !== null && Number(v) > 0),
+ );
+}
+
+/**
+ * Heatmap color scale bounds. A diverging palette is centred on 0 (the data
+ * range widened to be symmetric) unless `min` or `max` is given, so the
+ * middle color always means zero.
+ */
+function heatmapScale(
+ dataMin: number,
+ dataMax: number,
+ min: number | undefined,
+ max: number | undefined,
+ palette: ChartColorPalette,
+): { min: number; max: number } {
+ if (
+ palette === "diverging" &&
+ min === undefined &&
+ max === undefined &&
+ dataMin < 0 &&
+ dataMax > 0
+ ) {
+ const extent = Math.max(Math.abs(dataMin), Math.abs(dataMax));
+ return { min: -extent, max: extent };
+ }
+ const lo = min ?? dataMin;
+ const hi = max ?? dataMax;
+ // A zero-width range (all values equal, or min equal to max) gives a
+ // degenerate scale; widen it by 1 each way so cells take the middle color.
+ if (lo === hi) return { min: lo - 1, max: hi + 1 };
+ return { min: lo, max: hi };
+}
+
+/**
+ * Strips a line or area option down to a sparkline: no axes, legend, title or
+ * grid margins, and a y range fitted to the data so small changes show.
+ */
+function toSparkline(opt: Record): Record {
+ const hidden = (axis: unknown, extra: Record = {}) => ({
+ ...(axis as Record),
+ show: false,
+ name: "",
+ ...extra,
+ });
+ const { legend: _legend, title: _title, dataZoom: _zoom, ...rest } = opt;
+ return {
+ ...rest,
+ grid: { left: 2, right: 2, top: 4, bottom: 4, containLabel: false },
+ xAxis: hidden(opt.xAxis),
+ yAxis: Array.isArray(opt.yAxis)
+ ? opt.yAxis.map((axis) => hidden(axis, { scale: true }))
+ : hidden(opt.yAxis, { scale: true }),
+ };
+}
+
+/** Colors in the categorical palette before they repeat. */
+const MAX_DISTINCT_COLORS = 8;
+
+/** A `datazoom` event: the range, or the batch of ranges when several zooms move together. */
+interface ZoomEvent {
+ start?: number;
+ end?: number;
+ batch?: { start?: number; end?: number }[];
+}
+
+/** The zoom range and legend selection the reader set on the chart. */
+interface ReaderState {
+ zoom?: { start: number; end: number };
+ legend?: Record;
+}
+
+/**
+ * Carries the reader's zoom range and legend selection into a rebuilt option.
+ * Those components are replaced on update (so a removed series or legend entry
+ * leaves the chart), which would otherwise reset what the reader did.
+ */
+function keepReaderState(
+ option: EChartsOption,
+ state: ReaderState,
+): EChartsOption {
+ const { zoom, legend } = state;
+ const out = { ...option };
+ if (zoom && Array.isArray(option.dataZoom)) {
+ out.dataZoom = option.dataZoom.map((z) => ({ ...z, ...zoom }));
+ } else if (zoom && option.dataZoom) {
+ out.dataZoom = { ...option.dataZoom, ...zoom };
+ }
+ if (legend && option.legend && !Array.isArray(option.legend)) {
+ out.legend = { ...option.legend, selected: legend };
+ }
+ return out;
+}
+
+// ============================================================================
+// Bar Orientation
+// ============================================================================
+
+/** With `defaults="v3"`: most labels a vertical bar chart takes. */
+const VERTICAL_BAR_MAX_LABELS = 7;
+/** With `defaults="v3"`: longest label a vertical bar chart takes. */
+const VERTICAL_BAR_MAX_LABEL_LENGTH = 10;
+
+/**
+ * The v3 rule for a BarChart without `orientation`: numbers (such as years)
+ * and up to 7 short labels are vertical; anything else is horizontal. Time
+ * axes are vertical before this is asked.
+ */
+function fitsVerticalBars(xData: (string | number)[]): boolean {
+ if (xData.every((x) => typeof x === "number")) return true;
+ return (
+ xData.length <= VERTICAL_BAR_MAX_LABELS &&
+ xData.every((x) => String(x).length <= VERTICAL_BAR_MAX_LABEL_LENGTH)
+ );
+}
+
// ============================================================================
// Component Props
// ============================================================================
@@ -122,9 +356,17 @@ export interface BaseChartProps {
xKey?: string;
/** Y-axis field key(s) (auto-detected from schema if not provided) */
yKey?: string | string[];
- /** Chart orientation @default "vertical" */
+ /** X axis type override. Inferred from the `xKey` values when unset. */
+ xType?: XAxisType;
+ /** Column naming the series in long rows. See {@link ChartBaseProps.seriesKey}. */
+ seriesKey?: string;
+ /** Bar orientation (see `BarChartSpecificProps`). Ignored by other chart types. */
orientation?: Orientation;
- /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */
+ /**
+ * Chart height in pixels. Without it the chart fills its parent, at least
+ * 160 px (300 px with `defaults="v3"`). A className height such as
+ * `h-[400px]` also works.
+ */
height?: number;
/** Chart title */
title?: string;
@@ -141,38 +383,47 @@ export interface BaseChartProps {
colors?: string[];
/** Show data point symbols (line/area charts) @default false */
showSymbol?: boolean;
- /** Smooth line curves (line/area charts) @default true */
+ /** Smooth line curves (line/area charts). @default true (false with `defaults="v3"`) */
smooth?: boolean;
+ /** Connect line/area across missing values (v3 only) @default false */
+ connectNulls?: boolean;
/** Stack series @default false */
stacked?: boolean;
/** Symbol size for scatter charts @default 8 */
symbolSize?: number;
/** Show area fill for radar charts @default true */
showArea?: boolean;
- /** Inner radius for pie/donut (0-100) @default 0 */
+ /** Inner radius for pie/donut, in percent (0 up to 63, 90% of the outer radius). @default 0 (40 on DonutChart) */
innerRadius?: number;
/** Show labels on pie/donut slices @default true */
showLabels?: boolean;
/** Label position for pie/donut @default "outside" */
labelPosition?: "outside" | "inside" | "center";
+ /** Donut hole text, sized to fit; `true` shows the total (pie/donut). */
+ centerLabel?: string | boolean;
/** Y-axis field key for heatmap (the row dimension) */
yAxisKey?: string;
/** Min value for heatmap color scale */
min?: number;
/** Max value for heatmap color scale */
- max?: number;
+ /** Max value for the heatmap color scale; radar rim (one or per metric). */
+ max?: number | readonly number[];
/**
* Additional ECharts options to merge.
*
* Only the built-in feature set is registered by this package, so options
- * referencing extra ECharts features (`dataZoom`, `toolbox`, `markLine`,
+ * referencing extra ECharts features (`toolbox`, `brush`,
* `markArea`, `graphic`, `dataset`, top-level `axisPointer`, ...) require
* registering them in your app via `import { use } from "echarts/core"`.
* This only works when your `echarts` resolves to the same module
* instance/version as this package's (the registry is a singleton;
* duplicate echarts copies won't share registrations).
+ *
+ * An object is deep-merged into the built option (`series`, `xAxis`,
+ * `yAxis` and `grid` entry by entry). A function receives the built option
+ * and returns the option to render.
*/
- options?: Record;
+ options?: ChartOptionsInput;
/** Formats measure values. See {@link ChartBaseProps.valueFormatter}. */
valueFormatter?: ChartValueFormatter;
/** Additional CSS classes */
@@ -189,6 +440,27 @@ export interface BaseChartProps {
onDataClick?: (datum: ChartClickDatum) => void;
/** Controlled selection by category name. See {@link ChartBaseProps.selected}. */
selected?: string | string[];
+ /** Opt into the v3 defaults. See {@link ChartDefaults}. */
+ defaults?: ChartDefaults;
+ /** Target or reference lines (bar, line, area, scatter). */
+ referenceLines?: ChartReferenceLine[];
+ /** Zoom along the category or time axis (bar, line, area). */
+ zoom?: boolean;
+ /** Label each bar or scatter point with its value. */
+ showValues?: boolean;
+ /** Per-`yKey` series type and value axis (bar, line, area). */
+ series?: Record;
+ /** Heatmap aliases for xKey (columns), yAxisKey (rows) and yKey (values). */
+ columnKey?: string;
+ rowKey?: string;
+ valueKey?: string;
+ /** Heatmap column and row order overrides. */
+ xOrder?: readonly (string | number)[];
+ yOrder?: readonly (string | number)[];
+ /** Line/area: draw as a sparkline (no axes, legend or margins). */
+ sparkline?: boolean;
+ /** Radar: metric columns of one-row-per-entity data. */
+ metrics?: readonly string[];
}
// ============================================================================
@@ -200,25 +472,32 @@ export interface BaseChartProps {
* Renders using ECharts for consistent output across both formats.
*/
export function BaseChart({
- data,
+ data: dataProp,
chartType,
- xKey,
- yKey,
- orientation,
+ xKey: xKeyProp,
+ yKey: yKeyProp,
+ xType,
+ seriesKey,
+ orientation: orientationProp,
height,
title,
showLegend = true,
colorPalette,
colors: customColors,
showSymbol = false,
- smooth = true,
+ smooth: smoothProp,
+ connectNulls = false,
stacked = false,
symbolSize = 8,
showArea = true,
- innerRadius = 0,
- showLabels = true,
+ innerRadius,
+ showLabels: showLabelsProp,
labelPosition = "outside",
- yAxisKey,
+ centerLabel,
+ yAxisKey: yAxisKeyProp,
+ columnKey,
+ rowKey,
+ valueKey,
min,
max,
options: customOptions,
@@ -226,11 +505,73 @@ export function BaseChart({
className,
onDataClick,
selected,
+ defaults,
+ referenceLines,
+ zoom = false,
+ showValues = false,
+ series: seriesConfig,
+ metrics,
+ sparkline: sparklineProp = false,
+ xOrder,
+ yOrder,
}: BaseChartProps) {
+ // Radar with `metrics`: rows are entities; pivot to one row per metric.
+ const radarPivot = useMemo(
+ () =>
+ chartType === "radar" && metrics?.length
+ ? pivotRadarEntities(dataProp, xKeyProp, metrics)
+ : null,
+ [chartType, dataProp, xKeyProp, metrics],
+ );
+ const data = radarPivot?.rows ?? dataProp;
+ // Heatmap aliases: columnKey, rowKey and valueKey name the three roles.
+ const xKey = radarPivot ? RADAR_METRIC_KEY : (columnKey ?? xKeyProp);
+ const yKey = radarPivot ? radarPivot.entities : (valueKey ?? yKeyProp);
+ const yAxisKey = rowKey ?? yAxisKeyProp;
+ const v3 = defaults === "v3";
+ const sparkline =
+ sparklineProp && (chartType === "line" || chartType === "area");
+ // v3 pies and donuts carry name, value and share in the legend instead of
+ // slice labels, which overlap and get cut.
+ const showLabels =
+ showLabelsProp ?? !(v3 && (chartType === "pie" || chartType === "donut"));
+ // v3: straight lines. Smoothing invents values between points (a one-day
+ // spike draws as a bell weeks wide).
+ const smooth = smoothProp ?? !v3;
+ const sizeStyle = chartSizeStyle(height, { className, defaults });
+ // Only bars have an orientation. Line and area ignore it (it used to turn
+ // them into bar charts).
+ const orientation = chartType === "bar" ? orientationProp : undefined;
// Determine the appropriate color palette based on chart type
- const resolvedPalette = colorPalette ?? getDefaultPalette(chartType);
+ // A heatmap's scale is a ramp; a categorical palette made it a rainbow
+ // with no order, so heatmaps use the sequential palette instead.
+ const heatmapCategorical =
+ chartType === "heatmap" && colorPalette === "categorical";
+ const resolvedPalette = heatmapCategorical
+ ? "sequential"
+ : (colorPalette ?? getDefaultPalette(chartType));
const themeColors = useThemeColors(resolvedPalette);
- const colors = customColors ?? themeColors;
+ // Theme tokens such as var(--chart-cat-1) are resolved before ECharts.
+ const resolvedCustomColors = useResolvedColors(customColors);
+ const colors = resolvedCustomColors ?? themeColors;
+
+ // Radar polygons keep their color by name: a series' color used to follow
+ // its index, so removing the first series recolored the rest.
+ const seriesColorSlots = useRef(new Map());
+ const stableSeriesColors = (fields: string[]): string[] => {
+ const slots = seriesColorSlots.current;
+ const used = new Set(
+ fields.map((f) => slots.get(f)).filter((v) => v !== undefined),
+ );
+ for (const field of fields) {
+ if (slots.has(field)) continue;
+ let slot = 0;
+ while (used.has(slot)) slot++;
+ slots.set(field, slot);
+ used.add(slot);
+ }
+ return fields.map((f) => colors[(slots.get(f) ?? 0) % colors.length]);
+ };
const ui = useChartUITokens();
@@ -246,6 +587,16 @@ export function BaseChart({
// Store ECharts instance directly to avoid stale ref issues on unmount
const echartsInstanceRef = useRef(null);
+ // The reader's zoom range and legend selection, re-applied to each rebuilt option (see keepReaderState).
+ const readerStateRef = useRef({});
+
+ // The chart's width, rounded to 10 px, so axis labels can be truncated to
+ // the space they have. Unknown until mounted (and where ResizeObserver is
+ // missing), in which case labels are cut at a character count.
+ const [chartWidth, setChartWidth] = useState();
+ const [chartHeight, setChartHeight] = useState();
+ const resizeObserverRef = useRef(null);
+
// Callback ref pattern: captures the ECharts instance when ReactECharts mounts
// This ensures we always have a stable reference to the actual instance
const chartRefCallback = useCallback((node: ReactEChartsCore | null) => {
@@ -257,9 +608,22 @@ export function BaseChart({
echartsInstanceRef.current.dispose();
}
+ resizeObserverRef.current?.disconnect();
+ resizeObserverRef.current = null;
+
// Store the new instance
if (node) {
echartsInstanceRef.current = node.getEchartsInstance();
+ if (node.ele && typeof ResizeObserver !== "undefined") {
+ const observer = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width ?? 0;
+ const boxHeight = entries[0]?.contentRect.height ?? 0;
+ if (width > 0) setChartWidth(Math.round(width / 10) * 10);
+ if (boxHeight > 0) setChartHeight(Math.round(boxHeight / 10) * 10);
+ });
+ observer.observe(node.ele);
+ resizeObserverRef.current = observer;
+ }
} else {
// Component unmounting - dispose the stored instance
if (
@@ -272,18 +636,214 @@ export function BaseChart({
}
}, []);
+ // A key that is not in the rows would draw a flat zero series; report it.
+ const keyError = useMemo(
+ () =>
+ radarPivot
+ ? unknownKeysMessage(dataProp, { xKey: xKeyProp, metrics })
+ : unknownKeysMessage(data, {
+ [columnKey ? "columnKey" : "xKey"]: xKey,
+ [valueKey ? "valueKey" : "yKey"]: yKey,
+ [rowKey ? "rowKey" : "yAxisKey"]: yAxisKey,
+ seriesKey,
+ }),
+ [
+ radarPivot,
+ dataProp,
+ xKeyProp,
+ metrics,
+ data,
+ xKey,
+ yKey,
+ yAxisKey,
+ seriesKey,
+ columnKey,
+ rowKey,
+ valueKey,
+ ],
+ );
+
// Memoize data normalization
const normalized = useMemo(
() =>
chartType === "heatmap"
- ? normalizeHeatmapData(data, xKey, yAxisKey, yKey)
- : normalizeChartData(data, xKey, yKey, orientation),
- [data, xKey, yKey, yAxisKey, orientation, chartType],
+ ? normalizeHeatmapData(data, xKey, yAxisKey, yKey, {
+ keepNulls: v3,
+ xOrder,
+ yOrder,
+ })
+ : normalizeChartData(data, xKey, yKey, orientation, {
+ // Pie slices and radar spokes are names: never turn them into
+ // timestamps or numbers.
+ xType:
+ xType ??
+ (chartType === "pie" ||
+ chartType === "donut" ||
+ chartType === "radar"
+ ? "category"
+ : undefined),
+ // Scatter drops points with a missing value instead of plotting 0.
+ // Sparklines leave a gap at a missing day instead of a cliff to 0.
+ keepNulls: v3 || sparkline || chartType === "scatter",
+ seriesKey,
+ }),
+ [
+ data,
+ xKey,
+ yKey,
+ yAxisKey,
+ orientation,
+ chartType,
+ xType,
+ v3,
+ seriesKey,
+ xOrder,
+ yOrder,
+ sparkline,
+ ],
);
+ // Data a chart can't draw is reported instead of drawing an empty plot.
+ const isPieChart = chartType === "pie" || chartType === "donut";
+ const isRadarChart = chartType === "radar";
+ const chartError = useMemo(
+ () =>
+ keyError ??
+ (chartType === "scatter"
+ ? scatterXError(normalized)
+ : isPieChart && "yDataMap" in normalized
+ ? pieValueError(normalized)
+ : isRadarChart && "yDataMap" in normalized
+ ? radarValueError(normalized)
+ : "valueIsText" in normalized && normalized.valueIsText
+ ? `The value column "${normalized.yFields[0]}" holds text, so no cell can be drawn. A heatmap needs a column (xKey or columnKey), a row (yAxisKey or rowKey) and a numeric value (yKey or valueKey); "${String(normalized.yFields[0])}" looks like the row, so pass it as yAxisKey.`
+ : null),
+ [keyError, chartType, isPieChart, isRadarChart, normalized],
+ );
+ // All-zero pies used to draw a full ring of equal "0%" slices, and an
+ // all-zero radar a dot.
+ const pieEmpty =
+ (isPieChart || isRadarChart) &&
+ "yDataMap" in normalized &&
+ (isPieChart ? pieIsEmpty(normalized) : allZero(normalized));
+ useEffect(() => {
+ if (chartError) {
+ console.error(`[appkit-ui] ${chartType} chart: ${chartError}`);
+ }
+ }, [chartError, chartType]);
+
+ // The palette has 8 colors: past 8 series or slices, colors repeat.
+ const colorCount =
+ chartType === "pie" || chartType === "donut"
+ ? v3
+ ? 0
+ : normalized.xData.length
+ : chartType === "heatmap"
+ ? 0
+ : normalized.yFields.length;
+ useEffect(() => {
+ if (colorCount > MAX_DISTINCT_COLORS) {
+ console.warn(
+ `[appkit-ui] ${chartType} chart: ${colorCount} ${chartType === "pie" || chartType === "donut" ? "slices" : "series"} share ${MAX_DISTINCT_COLORS} colors, so colors repeat. Show the top ${MAX_DISTINCT_COLORS - 1} and group the rest as "Other" (pies do this with defaults="v3").`,
+ );
+ }
+ }, [colorCount, chartType]);
+
+ // ECharts stacks positive and negative values separately, so a stack with
+ // both signs draws bands that cross; say so.
+ const mixedSignStack = useMemo(() => {
+ if (!stacked || chartType !== "area" || !("yDataMap" in normalized)) {
+ return false;
+ }
+ let positive = false;
+ let negative = false;
+ for (const field of normalized.yFields) {
+ for (const v of normalized.yDataMap[field] ?? []) {
+ const n = Number(v);
+ if (v === null || !Number.isFinite(n)) continue;
+ if (n > 0) positive = true;
+ if (n < 0) negative = true;
+ }
+ }
+ return positive && negative;
+ }, [stacked, chartType, normalized]);
+ useEffect(() => {
+ if (mixedSignStack) {
+ console.warn(
+ "[appkit-ui] area chart: the stack mixes positive and negative values, so its bands cross. Stack values of one sign, or use a line or bar chart.",
+ );
+ }
+ }, [mixedSignStack]);
+
+ useEffect(() => {
+ if (chartType === "scatter" && symbolSize < 2) {
+ console.warn(
+ `[appkit-ui] scatter chart: symbolSize ${symbolSize} is too small to see; points are drawn at 2 px.`,
+ );
+ }
+ }, [chartType, symbolSize]);
+
+ useEffect(() => {
+ if (heatmapCategorical) {
+ console.warn(
+ '[appkit-ui] heatmap: colorPalette="categorical" has no order, so it can\'t show low to high; the sequential palette is used. Use "diverging" for values around a midpoint.',
+ );
+ }
+ }, [heatmapCategorical]);
+
+ // A pie shows one measure, and repeated slice names share a legend entry.
+ const pieWarning = useMemo(() => {
+ if (chartType !== "pie" && chartType !== "donut") return null;
+ if (normalized.yFields.length > 1) {
+ return `only the first yKey ("${normalized.yFields[0]}") is drawn; ${normalized.yFields
+ .slice(1)
+ .map((f) => `"${f}"`)
+ .join(", ")} ignored.`;
+ }
+ const seen = new Set();
+ for (const x of normalized.xData) {
+ const name = String(x);
+ if (seen.has(name)) {
+ return `slice name ${JSON.stringify(name)} appears more than once; the slices share one legend entry. Aggregate by name in SQL.`;
+ }
+ seen.add(name);
+ }
+ return null;
+ }, [chartType, normalized]);
+ useEffect(() => {
+ if (pieWarning)
+ console.warn(`[appkit-ui] ${chartType} chart: ${pieWarning}`);
+ }, [pieWarning, chartType]);
+
+ // Long rows without a seriesKey draw a sawtooth; say how to fix it.
+ const repeatedX = useMemo(() => {
+ if (seriesKey || !["bar", "line", "area"].includes(chartType)) return null;
+ const seen = new Set();
+ for (const x of normalized.xData) {
+ if (seen.has(x)) return x;
+ seen.add(x);
+ }
+ return null;
+ }, [normalized, seriesKey, chartType]);
+ useEffect(() => {
+ if (repeatedX !== null) {
+ console.warn(
+ `[appkit-ui] ${chartType} chart: x value ${JSON.stringify(repeatedX)} appears more than once. For long rows (x, series, value), pass seriesKey to draw one series per value.`,
+ );
+ }
+ }, [repeatedX, chartType]);
+
// Memoize option building
const option = useMemo(() => {
- const { xData, yFields, xField, chartType: detectedChartType } = normalized;
+ const {
+ xData,
+ yFields,
+ xField,
+ chartType: detectedChartType,
+ xAxisType,
+ xDateOnly,
+ } = normalized;
+ const isValueX = xAxisType === "value";
if (xData.length === 0) return null;
@@ -298,12 +858,26 @@ export function BaseChart({
xData,
yDataMap,
yFields,
- colors,
+ colors: chartType === "radar" ? stableSeriesColors(yFields) : colors,
title,
showLegend,
xField,
ui,
- valueFormatter,
+ // v3 without a formatter: compact ticks, full values in tooltips.
+ valueFormatter: valueFormatter ?? (v3 ? formatFullNumber : undefined),
+ axisValueFormatter:
+ valueFormatter ?? (v3 ? formatCompactNumber : undefined),
+ valueLabelFormatter:
+ valueFormatter ?? (v3 ? formatLabelNumber : undefined),
+ xIsTime: detectedChartType === "timeseries",
+ xDateOnly,
+ v3,
+ chartWidth,
+ chartHeight,
+ referenceLines,
+ zoom,
+ showValues,
+ seriesConfig,
};
const isPie = chartType === "pie" || chartType === "donut";
const isRadar = chartType === "radar";
@@ -312,9 +886,11 @@ export function BaseChart({
!isRadar &&
!isHeatmap &&
(orientation === "horizontal" ||
- (detectedChartType === "categorical" &&
- !orientation &&
- chartType === "bar"));
+ (!orientation &&
+ chartType === "bar" &&
+ detectedChartType === "categorical" &&
+ !isValueX &&
+ (!v3 || !fitsVerticalBars(xData))));
const isTimeSeries =
detectedChartType === "timeseries" &&
!isHorizontal &&
@@ -335,12 +911,18 @@ export function BaseChart({
...baseCtx,
yAxisData: heatmapNorm.yAxisData,
heatmapData: heatmapNorm.heatmapData,
- min: min ?? heatmapNorm.min,
- max: max ?? heatmapNorm.max,
- showLabels,
+ ...heatmapScale(
+ heatmapNorm.min,
+ heatmapNorm.max,
+ min,
+ typeof max === "number" ? max : undefined,
+ resolvedPalette,
+ ),
+ // Unset: labels when they fit the cells.
+ showLabels: showLabelsProp,
});
} else if (isRadar) {
- opt = buildRadarOption(baseCtx, showArea);
+ opt = buildRadarOption(baseCtx, showArea, max);
} else if (isPie) {
opt = buildPieOption(
baseCtx,
@@ -348,6 +930,7 @@ export function BaseChart({
innerRadius,
showLabels,
labelPosition,
+ { centerLabel },
);
} else if (isHorizontal) {
opt = buildHorizontalBarOption(baseCtx, stacked);
@@ -356,8 +939,10 @@ export function BaseChart({
...baseCtx,
chartType,
isTimeSeries,
+ isValueX: isValueX && !isHorizontal,
stacked,
smooth,
+ connectNulls,
showSymbol,
symbolSize,
interactive,
@@ -365,7 +950,8 @@ export function BaseChart({
}
// Apply selection after custom options; empty selection is a no-op.
- const merged = customOptions ? { ...opt, ...customOptions } : opt;
+ if (sparkline) opt = toSparkline(opt);
+ const merged = mergeChartOptions(opt, customOptions);
return applySelectionEmphasis(merged, selected);
}, [
normalized,
@@ -378,8 +964,10 @@ export function BaseChart({
innerRadius,
showLabels,
labelPosition,
+ centerLabel,
stacked,
smooth,
+ connectNulls,
showSymbol,
symbolSize,
showArea,
@@ -389,6 +977,14 @@ export function BaseChart({
valueFormatter,
selected,
interactive,
+ v3,
+ chartWidth,
+ chartHeight,
+ referenceLines,
+ zoom,
+ showValues,
+ seriesConfig,
+ sparkline,
]);
// Heatmap data uses axis indexes; preserve labels for click results instead
@@ -408,17 +1004,67 @@ export function BaseChart({
const axisLabelsRef = useRef(axisLabels);
axisLabelsRef.current = axisLabels;
+ // What a click resolves against: the source rows and x positions.
+ const clickContext = useMemo(
+ () => ({
+ chartType,
+ data,
+ xField: normalized.xField,
+ yFields: normalized.yFields,
+ xData: normalized.xData,
+ yDataMap: "yDataMap" in normalized ? normalized.yDataMap : undefined,
+ rowIndex: normalized.rowIndex,
+ cellRowIndex:
+ "cellRowIndex" in normalized
+ ? (normalized.cellRowIndex as number[])
+ : undefined,
+ seriesLabels: radarPivot
+ ? radarPivot.entities
+ : normalized.yFields.map((f) => formatLabel(f)),
+ seriesRows: radarPivot?.entityRows,
+ }),
+ [chartType, data, normalized, radarPivot],
+ );
+ const clickContextRef = useRef(clickContext);
+ clickContextRef.current = clickContext;
+
// Memoize by handler presence because echarts-for-react re-subscribes whenever
// `onEvents` changes, while callers commonly pass a new inline callback on
// every render. This also avoids churn during frequently changing data such
// as SSE ticks.
const onEvents = useMemo(
- () =>
- interactive
+ () => ({
+ // Refs, not state: remembering the reader's zoom and legend must not re-render the chart.
+ datazoom: (params: unknown) => {
+ const { batch, ...range } = params as ZoomEvent;
+ const { start, end } = batch?.[0] ?? range;
+ if (start !== undefined && end !== undefined) {
+ readerStateRef.current.zoom = { start, end };
+ }
+ },
+ legendselectchanged: (params: unknown) => {
+ readerStateRef.current.legend = (
+ params as { selected: Record }
+ ).selected;
+ },
+ ...(interactive
? {
click: (params: unknown, instance: ECharts) => {
+ const datum = mapToDatum(params, axisLabelsRef.current, instance);
+ const event = (params as { event?: Record })
+ ?.event;
+ const pointer =
+ typeof event?.offsetX === "number" &&
+ typeof event?.offsetY === "number"
+ ? { x: event.offsetX, y: event.offsetY }
+ : undefined;
const result = onDataClickRef.current?.(
- mapToDatum(params, axisLabelsRef.current, instance),
+ resolveClickDatum(
+ datum,
+ clickContextRef.current,
+ radarGeometry(instance),
+ pointer,
+ ),
) as void | Promise;
if (
result &&
@@ -428,15 +1074,28 @@ export function BaseChart({
}
},
}
- : undefined,
+ : {}),
+ }),
[interactive],
);
- if (!option) {
+ if (chartError) {
+ return (
+
+ {chartError}
+
+ );
+ }
+
+ if (!option || pieEmpty) {
return (
No data
@@ -447,11 +1106,13 @@ export function BaseChart({
diff --git a/packages/appkit-ui/src/react/charts/click.ts b/packages/appkit-ui/src/react/charts/click.ts
new file mode 100644
index 000000000..fcb20de26
--- /dev/null
+++ b/packages/appkit-ui/src/react/charts/click.ts
@@ -0,0 +1,188 @@
+import type { Table } from "apache-arrow";
+
+import { scatterPointIndices } from "./options";
+import type { ChartClickDatum, ChartData, ChartValue } from "./types";
+import { isArrowTable } from "./types";
+
+/** What a click needs to know about the chart it landed on. */
+export interface ClickContext {
+ chartType: string;
+ data: ChartData;
+ xField: string;
+ yFields: string[];
+ xData: (string | number)[];
+ yDataMap?: Record;
+ /** Source row of each x position (absent for pivoted long rows). */
+ rowIndex?: number[];
+ /** Heatmap: source row of each cell. */
+ cellRowIndex?: number[];
+ /** Series label of each y field, in order. */
+ seriesLabels: string[];
+ /** Radar with `metrics`: the entity row behind each series. */
+ seriesRows?: Record[];
+}
+
+interface RadarGeometry {
+ width: number;
+ height: number;
+ /** ECharts `radar.center`, `["50%", "50%"]` by default. */
+ center?: [string | number, string | number];
+ /** ECharts `radar.startAngle` in degrees. @default 90 */
+ startAngle?: number;
+ clockwise?: boolean;
+}
+
+function parsePosition(value: string | number, size: number): number {
+ if (typeof value === "number") return value;
+ const trimmed = value.trim();
+ return trimmed.endsWith("%")
+ ? (Number.parseFloat(trimmed) / 100) * size
+ : Number.parseFloat(trimmed);
+}
+
+/**
+ * Index of the radar spoke nearest a click at (`x`, `y`) in chart pixels,
+ * with ECharts' spoke layout: spoke `i` sits at `startAngle + i * 360 / count`
+ * degrees, counter-clockwise unless `clockwise`.
+ */
+export function nearestRadarIndicator(
+ x: number,
+ y: number,
+ count: number,
+ geometry: RadarGeometry,
+): number {
+ if (count <= 0) return -1;
+ const [cxRaw, cyRaw] = geometry.center ?? ["50%", "50%"];
+ const cx = parsePosition(cxRaw, geometry.width);
+ const cy = parsePosition(cyRaw, geometry.height);
+ const clickAngle = Math.atan2(cy - y, x - cx);
+ const start = ((geometry.startAngle ?? 90) * Math.PI) / 180;
+ const sign = geometry.clockwise ? -1 : 1;
+ let best = 0;
+ let bestDiff = Number.POSITIVE_INFINITY;
+ for (let i = 0; i < count; i++) {
+ const angle = start + (sign * i * Math.PI * 2) / count;
+ const diff = Math.abs(
+ Math.atan2(Math.sin(clickAngle - angle), Math.cos(clickAngle - angle)),
+ );
+ if (diff < bestDiff) {
+ bestDiff = diff;
+ best = i;
+ }
+ }
+ return best;
+}
+
+function sourceRow(
+ data: ChartData,
+ index: number | undefined,
+): Record | undefined {
+ if (index === undefined || index < 0) return undefined;
+ if (isArrowTable(data)) {
+ const row = (data as Table).get(index);
+ return row ? (row.toJSON() as Record) : undefined;
+ }
+ return (data as Record[])[index];
+}
+
+/** The x value as it is in the source row, as a string. */
+function originalName(value: unknown): string | undefined {
+ if (value === null || value === undefined) return undefined;
+ if (value instanceof Date) return value.toISOString();
+ if (typeof value === "bigint") return value.toString();
+ return String(value);
+}
+
+/** ECharts names unnamed series with a NUL-containing placeholder. */
+function cleanSeriesName(name: string | undefined): string | undefined {
+ return name === undefined || name.includes("\u0000") ? undefined : name;
+}
+
+/**
+ * Completes a click datum with the source row and the original x value as
+ * `name`. On a time axis ECharts reports an empty name (bars, symbols) or the
+ * epoch milliseconds (line strokes); scatter data indices count only the
+ * plotted points; pie and heatmap series are unnamed; and a radar click names
+ * the polygon, not the metric.
+ */
+export function resolveClickDatum(
+ datum: ChartClickDatum,
+ ctx: ClickContext,
+ geometry?: RadarGeometry,
+ pointer?: { x: number; y: number },
+): ChartClickDatum {
+ const raw = (datum.raw ?? {}) as Record;
+ const rawData = raw.data as Record | undefined;
+ const result: ChartClickDatum = {
+ ...datum,
+ seriesName: cleanSeriesName(datum.seriesName),
+ };
+ let position: number | undefined;
+
+ switch (ctx.chartType) {
+ case "pie":
+ case "donut": {
+ const index = rawData?.sourceIndex;
+ position = typeof index === "number" ? index : undefined;
+ break;
+ }
+ case "heatmap": {
+ const rowIdx = ctx.cellRowIndex?.[datum.dataIndex];
+ result.row = sourceRow(ctx.data, rowIdx);
+ if (datum.x !== undefined) result.name = String(datum.x);
+ result.seriesName = cleanSeriesName(datum.seriesName) ?? undefined;
+ return result;
+ }
+ case "radar": {
+ const seriesLabel = ctx.seriesLabels[datum.dataIndex];
+ result.seriesName = seriesLabel;
+ if (pointer && geometry) {
+ const spoke = nearestRadarIndicator(
+ pointer.x,
+ pointer.y,
+ ctx.xData.length,
+ geometry,
+ );
+ position = spoke;
+ const field = ctx.yFields[datum.dataIndex];
+ const value = field ? ctx.yDataMap?.[field]?.[spoke] : undefined;
+ result.value = value ?? null;
+ } else {
+ return result;
+ }
+ break;
+ }
+ case "scatter": {
+ const field = ctx.yFields[datum.seriesIndex];
+ const yData = field ? ctx.yDataMap?.[field] : undefined;
+ position = yData
+ ? scatterPointIndices(ctx.xData, yData)[datum.dataIndex]
+ : undefined;
+ break;
+ }
+ default:
+ position = datum.dataIndex >= 0 ? datum.dataIndex : undefined;
+ }
+
+ if (position === undefined) return result;
+ const rowIdx = ctx.rowIndex?.[position];
+ const row = sourceRow(ctx.data, rowIdx);
+ if (row) result.row = row;
+ const xValue = row
+ ? originalName(row[ctx.xField])
+ : originalName(ctx.xData[position]);
+ if (
+ xValue !== undefined &&
+ ctx.chartType !== "pie" &&
+ ctx.chartType !== "donut"
+ ) {
+ result.name = xValue;
+ }
+ if (ctx.chartType === "radar" && ctx.xData[position] !== undefined) {
+ result.name = String(ctx.xData[position]);
+ const entityRow = ctx.seriesRows?.[datum.dataIndex];
+ if (entityRow) result.row = entityRow;
+ }
+ if (ctx.chartType === "scatter") result.dataIndex = rowIdx ?? position;
+ return result;
+}
diff --git a/packages/appkit-ui/src/react/charts/constants.ts b/packages/appkit-ui/src/react/charts/constants.ts
index 8eda4ac0f..3ab6650be 100644
--- a/packages/appkit-ui/src/react/charts/constants.ts
+++ b/packages/appkit-ui/src/react/charts/constants.ts
@@ -2,7 +2,7 @@
// Shared Constants for Chart Components
// ============================================================================
-import type { ChartUITokens } from "./types";
+import type { ChartDefaults, ChartUITokens } from "./types";
// Re-export field patterns from shared constants
export {
@@ -126,15 +126,36 @@ export const FALLBACK_UI_TOKENS: ChartUITokens = {
/** Smallest height a chart takes when it fills its parent (no `height` prop). */
export const CHART_MIN_HEIGHT = 160;
+/** With `defaults="v3"`: the height a chart takes when its parent has none. */
+const CHART_V3_MIN_HEIGHT = 300;
+
+/**
+ * Matches a Tailwind height utility in a className (`h-[400px]`, `md:h-96`,
+ * `size-80`), but not `min-h-*` or `max-h-*`.
+ */
+const CLASS_HEIGHT_PATTERN = /(?:^|\s)(?:[\w-]+:)*!?(?:h|size)-\S/;
+
/**
- * A chart's box: exactly `height` pixels, or its parent's height, at least
- * {@link CHART_MIN_HEIGHT} when that comes from its content.
+ * A chart's box: exactly `height` pixels; no inline height when `className`
+ * sets one (so `h-[400px]` takes effect); otherwise its parent's height, at
+ * least {@link CHART_MIN_HEIGHT} (300 px with `defaults="v3"`) when that
+ * comes from its content.
*/
-export function chartSizeStyle(height?: number): {
- height: number | string;
+export function chartSizeStyle(
+ height?: number,
+ opts: { className?: string; defaults?: ChartDefaults } = {},
+): {
+ height?: number | string;
minHeight?: number;
} {
- return height !== undefined
- ? { height }
- : { height: "100%", minHeight: CHART_MIN_HEIGHT };
+ if (height !== undefined) return { height };
+ const minHeight =
+ opts.defaults === "v3" ? CHART_V3_MIN_HEIGHT : CHART_MIN_HEIGHT;
+ // A height class (h-full, md:h-96, h-[400px]) sets the box, and an inline
+ // 100% would beat a breakpoint class, so no inline height. The minimum still
+ // applies, so a class that depends on a parent with no height cannot collapse.
+ if (opts.className && CLASS_HEIGHT_PATTERN.test(opts.className)) {
+ return { minHeight };
+ }
+ return { height: "100%", minHeight };
}
diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx
index d040257ba..abf8b27db 100644
--- a/packages/appkit-ui/src/react/charts/create-chart.tsx
+++ b/packages/appkit-ui/src/react/charts/create-chart.tsx
@@ -1,7 +1,181 @@
import { BaseChart } from "./base";
-import type { ChartData, ChartType, UnifiedChartProps } from "./types";
+import type {
+ AreaChartSpecificProps,
+ BarChartSpecificProps,
+ ChartBaseProps,
+ ChartData,
+ ChartDefaults,
+ ChartType,
+ HeatmapChartSpecificProps,
+ LineChartSpecificProps,
+ PieChartSpecificProps,
+ RadarChartSpecificProps,
+ ScatterChartSpecificProps,
+ UnifiedChartProps,
+} from "./types";
+import { formatLabel } from "./utils";
import { ChartWrapper } from "./wrapper";
+/**
+ * Lists every key of `T`. The argument fails to type-check when a key of `T`
+ * is missing, so these lists can't drift from the prop interfaces.
+ */
+function allKeys() {
+ return (
+ keys: K & ([keyof T] extends [K[number]] ? unknown : never),
+ ): readonly string[] => keys as readonly string[];
+}
+
+const SHARED_PROPS = [
+ ...allKeys()([
+ "title",
+ "showLegend",
+ "colorPalette",
+ "colors",
+ "height",
+ "className",
+ "xKey",
+ "yKey",
+ "seriesKey",
+ "xType",
+ "defaults",
+ "ariaLabel",
+ "testId",
+ "options",
+ "valueFormatter",
+ "onDataClick",
+ "selected",
+ ]),
+ // Query and data mode props.
+ "queryKey",
+ "parameters",
+ "format",
+ "transformer",
+ "data",
+ "loading",
+ "error",
+];
+
+const PIE_PROPS = allKeys()([
+ "innerRadius",
+ "showLabels",
+ "labelPosition",
+ "centerLabel",
+]);
+
+/** Props each chart type reads, beyond the shared ones. */
+const CHART_PROPS: Record = {
+ bar: allKeys()([
+ "orientation",
+ "stacked",
+ "referenceLines",
+ "zoom",
+ "showValues",
+ "series",
+ ]),
+ line: allKeys()([
+ "sparkline",
+ "referenceLines",
+ "zoom",
+ "series",
+ "symbolSize",
+ "showSymbol",
+ "smooth",
+ "connectNulls",
+ ]),
+ area: allKeys()([
+ "sparkline",
+ "referenceLines",
+ "zoom",
+ "series",
+ "symbolSize",
+ "showSymbol",
+ "smooth",
+ "connectNulls",
+ "stacked",
+ ]),
+ scatter: allKeys()([
+ "symbolSize",
+ "referenceLines",
+ "showValues",
+ ]),
+ pie: PIE_PROPS,
+ donut: PIE_PROPS,
+ radar: allKeys()(["showArea", "max", "metrics"]),
+ heatmap: allKeys()([
+ "yAxisKey",
+ "min",
+ "max",
+ "showLabels",
+ "xOrder",
+ "yOrder",
+ "columnKey",
+ "rowKey",
+ "valueKey",
+ ]),
+};
+
+const CHART_TYPE_NAMES: Record = {
+ bar: "Bar chart",
+ line: "Line chart",
+ area: "Area chart",
+ pie: "Pie chart",
+ donut: "Donut chart",
+ scatter: "Scatter chart",
+ radar: "Radar chart",
+ heatmap: "Heatmap",
+};
+
+/**
+ * Accessible name for a chart without `ariaLabel`, from its type and fields:
+ * "Bar chart of revenue, cost by month".
+ */
+function defaultAriaLabel(
+ chartType: ChartType,
+ title: unknown,
+ xKey: unknown,
+ yKey: unknown,
+): string {
+ const type = CHART_TYPE_NAMES[chartType];
+ if (typeof title === "string" && title) return `${type}: ${title}`;
+ const ys = (Array.isArray(yKey) ? yKey : yKey ? [yKey] : []).map((y) =>
+ formatLabel(String(y)).toLowerCase(),
+ );
+ const x =
+ typeof xKey === "string" && xKey ? formatLabel(xKey).toLowerCase() : "";
+ if (ys.length && x) return `${type} of ${ys.join(", ")} by ${x}`;
+ if (ys.length) return `${type} of ${ys.join(", ")}`;
+ if (x) return `${type} by ${x}`;
+ return type;
+}
+
+const warnedUnknownProps = new Set();
+
+/**
+ * In development, warns once per chart type and prop set about props this chart type ignores
+ * (e.g. `min` on a radar), which TypeScript only catches without casts.
+ */
+function warnUnknownProps(
+ chartType: ChartType,
+ displayName: string,
+ props: object,
+) {
+ if (!import.meta.env?.DEV) return;
+ const known = new Set([...SHARED_PROPS, ...CHART_PROPS[chartType]]);
+ const unknown = Object.entries(props)
+ .filter(([key, value]) => !known.has(key) && value !== undefined)
+ .map(([key]) => key);
+ const message = unknown.length
+ ? `${displayName} ignores ${unknown.join(",")}`
+ : "";
+ if (message && !warnedUnknownProps.has(message)) {
+ warnedUnknownProps.add(message);
+ console.warn(
+ `[appkit-ui] ${displayName} ignores ${unknown.map((k) => `\`${k}\``).join(", ")}.`,
+ );
+ }
+}
+
/**
* Factory function to create chart components.
* Eliminates boilerplate by generating components with the same pattern.
@@ -21,6 +195,7 @@ export function createChart(
displayName: string,
) {
const Component = (props: TProps) => {
+ warnUnknownProps(chartType, displayName, props);
const {
// Query props
queryKey,
@@ -29,11 +204,14 @@ export function createChart(
transformer,
// Data props
data,
+ loading,
+ error,
// Common props
- height,
+ height: heightProp,
className,
ariaLabel,
testId,
+ defaults,
// All remaining props pass through to BaseChart
...chartProps
} = props as TProps & {
@@ -42,17 +220,43 @@ export function createChart(
format?: string;
transformer?: unknown;
data?: unknown;
+ loading?: boolean;
+ error?: string | Error | null;
height?: number;
className?: string;
ariaLabel?: string;
testId?: string;
+ defaults?: ChartDefaults;
};
+ // A sparkline is a 48 px strip unless told otherwise.
+ const height =
+ heightProp ??
+ ((chartProps as { sparkline?: boolean }).sparkline ? 48 : undefined);
+
+ const label =
+ ariaLabel ??
+ defaultAriaLabel(
+ chartType,
+ chartProps.title,
+ chartProps.xKey,
+ chartProps.yKey,
+ );
+
const wrapperProps =
data !== undefined
? // ChartDataInput also admits interface-typed and readonly rows; at
// runtime they're the same plain objects the chart reads.
- { data: data as ChartData, height, className, ariaLabel, testId }
+ {
+ data: data as ChartData,
+ loading,
+ error,
+ height,
+ className,
+ ariaLabel: label,
+ testId,
+ defaults,
+ }
: {
queryKey: queryKey as string,
parameters,
@@ -60,8 +264,9 @@ export function createChart(
transformer,
height,
className,
- ariaLabel,
+ ariaLabel: label,
testId: testId ?? `${chartType}-chart-${queryKey}`,
+ defaults,
};
return (
@@ -72,6 +277,7 @@ export function createChart(
chartType={chartType}
height={height}
className={className}
+ defaults={defaults}
{...chartProps}
/>
)}
diff --git a/packages/appkit-ui/src/react/charts/heatmap/examples/heatmap.example.tsx b/packages/appkit-ui/src/react/charts/heatmap/examples/heatmap.example.tsx
index 762bec054..638a24819 100644
--- a/packages/appkit-ui/src/react/charts/heatmap/examples/heatmap.example.tsx
+++ b/packages/appkit-ui/src/react/charts/heatmap/examples/heatmap.example.tsx
@@ -1,28 +1,28 @@
-"use client";
-
import { HeatmapChart } from "@databricks/appkit-ui/react";
-export default function HeatmapChartExample() {
- const data = [];
- const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
- const hours = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"];
-
- for (const day of days) {
- for (const hour of hours) {
- data.push({
- day,
- hour,
- count: Math.floor(Math.random() * 100),
- });
- }
- }
+// One row per cell, as `config/queries/orders_by_hour.sql` returns them.
+// Weekdays are put in calendar order whatever the row order.
+// SELECT DATE_FORMAT(created_at, 'E') AS weekday, HOUR(created_at) AS hour,
+// COUNT(*) AS orders
+// FROM orders GROUP BY 1, 2
+const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
+const hours = [8, 10, 12, 14, 16, 18];
+const rows = weekdays.flatMap((weekday, d) =>
+ hours.map((hour, h) => ({
+ weekday,
+ hour,
+ // Busy at lunch and on weekdays: a fixed pattern, not random data.
+ orders: (d < 5 ? 60 : 25) + (h === 2 ? 40 : 0) + ((d * 7 + h * 3) % 11),
+ })),
+);
+export default function HeatmapChartExample() {
return (
);
diff --git a/packages/appkit-ui/src/react/charts/heatmap/index.tsx b/packages/appkit-ui/src/react/charts/heatmap/index.tsx
index 7dc450152..305a6eaf5 100644
--- a/packages/appkit-ui/src/react/charts/heatmap/index.tsx
+++ b/packages/appkit-ui/src/react/charts/heatmap/index.tsx
@@ -4,16 +4,24 @@ import type { HeatmapChartProps } from "../types";
/**
* Heatmap Chart component for matrix-style data visualization.
*
+ * **Use when:** finding where a measure is high or low across two dimensions (weekday by hour, cohort by period).
+ *
+ * **Not when:** under 3 by 3 cells (grouped BarChart); over 30 columns (aggregate in SQL).
+ *
+ * **Rows:** one per cell; name the roles with `columnKey`, `rowKey` and `valueKey`.
+ *
+ * **Gotchas:** repeated cells are summed with a warning; weekdays, months, numbers and dates are put in order (`xOrder`/`yOrder` override). Use `colorPalette="diverging"` for values around 0.
+ *
* **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
*
- * **Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+ * **Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+ * elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+ * the UI is built first; add `loading` and `error` so the chart shows those states in its box.
*
* Data should be in "long format" with three fields:
- * - xKey: X-axis category (columns)
- * - yAxisKey: Y-axis category (rows)
- * - yKey: The numeric value for each cell
- *
- * Supports both query mode (queryKey + parameters) and data mode (static data).
+ * - columnKey (or xKey): X-axis category (columns)
+ * - rowKey (or yAxisKey): Y-axis category (rows)
+ * - valueKey (or yKey): The numeric value for each cell
*/
export const HeatmapChart = createChart(
"heatmap",
diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts
index 0cd6723b4..5ab68cbfa 100644
--- a/packages/appkit-ui/src/react/charts/index.ts
+++ b/packages/appkit-ui/src/react/charts/index.ts
@@ -33,6 +33,7 @@ export { ChartWrapper, type ChartWrapperProps } from "./wrapper";
export {
type NormalizedHeatmapData,
+ type NormalizeOptions,
normalizeChartData,
normalizeHeatmapData,
} from "./normalize";
@@ -109,7 +110,11 @@ export type {
ChartColorPalette,
ChartData,
ChartDataInput,
+ ChartDefaults,
+ ChartReferenceLine,
+ ChartSeriesConfig,
ChartRow,
+ ChartTransformer,
ChartType,
ChartUITokens,
ChartValueFormatter,
@@ -132,6 +137,7 @@ export type {
ScatterChartProps,
ScatterChartSpecificProps,
UnifiedChartProps,
+ XAxisType,
} from "./types";
// Type guards
diff --git a/packages/appkit-ui/src/react/charts/line/examples/line.example.tsx b/packages/appkit-ui/src/react/charts/line/examples/line.example.tsx
index ea64ff8d6..68f0fdecf 100644
--- a/packages/appkit-ui/src/react/charts/line/examples/line.example.tsx
+++ b/packages/appkit-ui/src/react/charts/line/examples/line.example.tsx
@@ -1,21 +1,28 @@
-"use client";
-
import { LineChart } from "@databricks/appkit-ui/react";
+// Rows as `config/queries/daily_orders.sql` returns them: a DATE column and a
+// count, one row per day. A day with no data is null and shows as a gap with
+// `defaults="v3"`.
+// SELECT order_date, COUNT(*) AS orders FROM orders
+// WHERE order_date >= :start_date GROUP BY order_date ORDER BY order_date
+// In an app:
+const rows = [
+ { order_date: "2026-03-01", orders: 182 },
+ { order_date: "2026-03-02", orders: 205 },
+ { order_date: "2026-03-03", orders: 198 },
+ { order_date: "2026-03-04", orders: null },
+ { order_date: "2026-03-05", orders: 231 },
+ { order_date: "2026-03-06", orders: 264 },
+ { order_date: "2026-03-07", orders: 249 },
+];
+
export default function LineChartExample() {
return (
);
diff --git a/packages/appkit-ui/src/react/charts/line/index.tsx b/packages/appkit-ui/src/react/charts/line/index.tsx
index 2426717db..ed5fa717b 100644
--- a/packages/appkit-ui/src/react/charts/line/index.tsx
+++ b/packages/appkit-ui/src/react/charts/line/index.tsx
@@ -4,10 +4,18 @@ import type { LineChartProps } from "../types";
/**
* Line Chart component for time-series and trend visualization.
*
- * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
+ * **Use when:** a measure changes over time.
+ *
+ * **Not when:** under 4 periods (vertical BarChart); over 5 series (top 4 plus "Other" in SQL).
+ *
+ * **Rows:** one per period, a DATE or TIMESTAMP column and a measure; several series as one column each or long rows plus `seriesKey`.
*
- * **Best Practice:** Use the built-in data fetching by passing `queryKey` and `parameters` props instead of pre-fetching data with `useAnalyticsQuery`.
+ * **Gotchas:** the x axis is a time axis only when every `xKey` value is a date. Missing values draw as 0 unless `defaults="v3"`, which leaves a gap. Lines are smoothed unless `smooth={false}` or `defaults="v3"`. For a KPI tile use `sparkline`.
+ *
+ * **Important:** This component uses Apache ECharts architecture. Configure it via props, not by passing child components.
*
- * Supports both query mode (queryKey + parameters) and data mode (static data).
+ * **Data:** pass `queryKey` (and `parameters`) when the chart owns its query. Pass `data={rows}` when several
+ * elements share one result (a KPI, a chart and a table fed by one `useAnalyticsQuery`), or for stub rows while
+ * the UI is built first; add `loading` and `error` so the chart shows those states in its box.
*/
export const LineChart = createChart("line", "LineChart");
diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts
index 93c624c18..c59d21e55 100644
--- a/packages/appkit-ui/src/react/charts/normalize.ts
+++ b/packages/appkit-ui/src/react/charts/normalize.ts
@@ -1,19 +1,24 @@
import type { Table } from "apache-arrow";
import { ArrowClient } from "@/js";
+import { ARROW_TYPE_IDS, getTypeIdSets } from "@/js/arrow/lazy-arrow";
-import { DATE_FIELD_PATTERNS, NAME_FIELD_PATTERNS } from "./constants";
+import { METADATA_DATE_PATTERNS, NAME_FIELD_PATTERNS } from "./constants";
import type {
ChartData,
+ ChartValue,
NormalizedChartData,
NormalizedChartDataBase,
Orientation,
+ XAxisType,
} from "./types";
import { isArrowTable } from "./types";
import {
+ isDateOnlyColumn,
sortNumericAscending,
sortTimeSeriesAscending,
toChartArray,
+ toChartValue,
toChronologicalValue,
} from "./utils";
@@ -56,65 +61,117 @@ function isCategoryValue(value: unknown): boolean {
return Number.isNaN(parsed) || !Number.isFinite(parsed);
}
+function isMissing(value: unknown): boolean {
+ return value === null || value === undefined || value === "";
+}
+
+/**
+ * Infers an x axis type from a column's values, ignoring missing ones: all
+ * dates gives `"time"`, anything else `"category"`. Column names play no part.
+ */
+function inferXType(values: readonly unknown[]): XAxisType {
+ let dates = 0;
+ let others = 0;
+ for (const value of values) {
+ if (isMissing(value)) continue;
+ if (value instanceof Date || isDateString(value)) dates++;
+ else others++;
+ }
+ if (dates === 0) return "category";
+ // A stray non-date (such as "TBD") among at least three dates still makes a
+ // time axis; the stray rows are left off it with a warning.
+ const tolerated =
+ dates >= 3 ? Math.max(1, Math.floor((dates + others) / 10)) : 0;
+ return others <= tolerated ? "time" : "category";
+}
+
+function columnValues(data: Record[], key: string): unknown[] {
+ return data.map((row) => row[key]);
+}
+
// ============================================================================
// Field Detection
// ============================================================================
+/** What a column holds, when its type is known (Arrow schema). */
+type FieldKind = "time" | "numeric" | "string" | "other";
+
+interface FieldSource {
+ keys: string[];
+ /** All values of a column. */
+ values: (key: string) => unknown[];
+ /** The column's declared type, when known (Arrow); JSON has none. */
+ kind?: (key: string) => FieldKind;
+}
+
+function firstPresent(values: unknown[]): unknown {
+ for (const value of values) if (!isMissing(value)) return value;
+ return undefined;
+}
+
/**
- * Detects fields from JSON data for charting
+ * Detects the x and y fields. This is the one detection path for JSON rows
+ * and Arrow tables: an Arrow column's declared type is used when known, and
+ * otherwise the same value rules apply to both. Column names only rank
+ * candidates (a `name` column before other text, metadata dates such as
+ * `created_at` last); they never decide whether a column is a date.
*/
-function detectFieldsFromJson(
- data: Record[],
+function detectFields(
+ source: FieldSource,
orientation?: Orientation,
): {
xField: string;
yFields: string[];
chartType: "timeseries" | "categorical";
} {
- if (!data || data.length === 0) {
+ const { keys } = source;
+ if (keys.length === 0) {
return { xField: "x", yFields: ["y"], chartType: "categorical" };
}
-
- const firstRow = data[0];
- const keys = Object.keys(firstRow);
-
- // Detect date fields by key name OR by value being a date string
- const dateFields = keys.filter((key) => {
- const value = firstRow[key];
- const keyMatchesDatePattern = DATE_FIELD_PATTERNS.some((p) =>
- key.toLowerCase().includes(p),
+ const kindOf = (key: string) => source.kind?.(key);
+
+ // Date fields are decided by their values (or declared type), never by
+ // their names: a measure named `avg_response_time` is not a date.
+ const isMetadataDate = (key: string) =>
+ METADATA_DATE_PATTERNS.some((p) => key.toLowerCase().includes(p));
+ const dateFields = keys
+ .filter((key) => {
+ const kind = kindOf(key);
+ if (kind === "time") return true;
+ if (kind === "numeric") return false;
+ return inferXType(source.values(key)) === "time";
+ })
+ .sort((a, b) => Number(isMetadataDate(a)) - Number(isMetadataDate(b)));
+
+ const isCategoryField = (key: string) => {
+ const kind = kindOf(key);
+ if (kind !== undefined && kind !== "string") return false;
+ return (
+ !dateFields.includes(key) &&
+ isCategoryValue(firstPresent(source.values(key)))
);
- const valueIsDateString = isDateString(value);
- return keyMatchesDatePattern || valueIsDateString;
- });
+ };
// Detect name/category fields by pattern AND value type
- let nameFields = keys.filter((key) => {
- const value = firstRow[key];
- return (
- isCategoryValue(value) &&
- !isDateString(value) &&
- NAME_FIELD_PATTERNS.some((p) => key.toLowerCase().includes(p))
- );
- });
+ let nameFields = keys.filter(
+ (key) =>
+ isCategoryField(key) &&
+ NAME_FIELD_PATTERNS.some((p) => key.toLowerCase().includes(p)),
+ );
- // Fallback: any string field that isn't a date or ID
+ // Fallback: any text field that isn't a date or ID
if (nameFields.length === 0) {
- nameFields = keys.filter((key) => {
- const value = firstRow[key];
- return (
- isCategoryValue(value) &&
- !isDateString(value) &&
- !dateFields.includes(key) &&
- !key.toLowerCase().endsWith("_id")
- );
- });
+ nameFields = keys.filter(
+ (key) => isCategoryField(key) && !key.toLowerCase().endsWith("_id"),
+ );
}
// Detect numeric fields
const numericFields = keys.filter((key) => {
- const value = firstRow[key];
- return isNumericValue(value) && !dateFields.includes(key);
+ if (dateFields.includes(key)) return false;
+ const kind = kindOf(key);
+ if (kind !== undefined) return kind === "numeric";
+ return isNumericValue(firstPresent(source.values(key)));
});
const isHorizontal = orientation === "horizontal";
@@ -138,6 +195,50 @@ function detectFieldsFromJson(
};
}
+/** Detects fields from JSON rows. */
+function detectFieldsFromJson(
+ data: Record[],
+ orientation?: Orientation,
+): ReturnType {
+ if (!data || data.length === 0) {
+ return { xField: "x", yFields: ["y"], chartType: "categorical" };
+ }
+ return detectFields(
+ { keys: Object.keys(data[0]), values: (key) => columnValues(data, key) },
+ orientation,
+ );
+}
+
+/** Detects fields from an Arrow table with the same rules as JSON rows. */
+function detectFieldsFromTable(
+ table: Table,
+ orientation?: Orientation,
+): ReturnType {
+ const ids = getTypeIdSets();
+ const fields = table.schema.fields;
+ const byName = new Map(fields.map((f) => [f.name, f]));
+ return detectFields(
+ {
+ keys: fields.map((f) => f.name),
+ values: (key) => {
+ const col = table.getChild(key);
+ const out: unknown[] = [];
+ if (col) for (let i = 0; i < col.length; i++) out.push(col.get(i));
+ return out;
+ },
+ kind: (key) => {
+ const typeId = byName.get(key)?.typeId;
+ if (typeId === undefined) return "other";
+ if (ids.temporal.has(typeId)) return "time";
+ if (ids.numeric.has(typeId)) return "numeric";
+ if (ids.string.has(typeId)) return "string";
+ return "other";
+ },
+ },
+ orientation,
+ );
+}
+
// ============================================================================
// Value Conversion
// ============================================================================
@@ -151,7 +252,7 @@ function jsonValueToChartValue(
isDateField: boolean,
): string | number {
if (value === null || value === undefined) {
- return isYValue ? 0 : "";
+ return isYValue ? 0 : NULL_X_LABEL;
}
if (typeof value === "number") {
return value;
@@ -159,6 +260,10 @@ function jsonValueToChartValue(
if (typeof value === "bigint") {
return Number(value);
}
+ if (value instanceof Date) {
+ // A JS Date is a time value, never a "Wed Dec 31 ..." category string.
+ return value.getTime();
+ }
if (typeof value === "string") {
if (isDateField) {
const timestamp = toChronologicalValue(value);
@@ -189,23 +294,28 @@ function extractFromJson(
data: Record[],
xField: string,
yFields: string[],
+ xIsDateField: boolean,
+ keepNulls: boolean,
): {
xData: (string | number)[];
- yDataMap: Record;
+ yDataMap: Record;
} {
const xData: (string | number)[] = [];
- const yDataMap: Record = {};
+ const yDataMap: Record = {};
for (const field of yFields) {
yDataMap[field] = [];
}
- const xIsDateField = data.length > 0 && isDateString(data[0][xField]);
-
for (const row of data) {
xData.push(jsonValueToChartValue(row[xField], false, xIsDateField));
for (const field of yFields) {
- yDataMap[field].push(jsonValueToChartValue(row[field], true, false));
+ const value = row[field];
+ yDataMap[field].push(
+ keepNulls && isMissing(value)
+ ? null
+ : jsonValueToChartValue(value, true, false),
+ );
}
}
@@ -220,96 +330,485 @@ function extractFromJson(
* Normalizes chart data from either Arrow or JSON format.
* Converts BigInt and Date values to chart-compatible types.
*/
+/**
+ * Resolves the x and y keys. A key the caller gave is never auto-detected for
+ * the other axis, so `xKey` alone can't also become the only y field.
+ */
+function resolveKeys(
+ detected: { xField: string; yFields: string[] },
+ allKeys: string[],
+ xKey: string | undefined,
+ yKey: string | string[] | undefined,
+): { resolvedXKey: string; resolvedYKeys: string[] } {
+ const givenY = yKey ? (Array.isArray(yKey) ? yKey : [yKey]) : undefined;
+ const resolvedXKey =
+ xKey ??
+ (givenY?.includes(detected.xField)
+ ? (allKeys.find((k) => !givenY.includes(k)) ?? detected.xField)
+ : detected.xField);
+ if (givenY) return { resolvedXKey, resolvedYKeys: givenY };
+ const detectedY = detected.yFields.filter((k) => k !== resolvedXKey);
+ const resolvedYKeys =
+ detectedY.length > 0
+ ? detectedY
+ : allKeys.filter((k) => k !== resolvedXKey).slice(0, 1);
+ return {
+ resolvedXKey,
+ resolvedYKeys: resolvedYKeys.length > 0 ? resolvedYKeys : detected.yFields,
+ };
+}
+
+/** Column names available in chart data (Arrow schema, or keys of any row). */
+function availableKeys(data: ChartData): string[] {
+ if (isArrowTable(data)) return data.schema.fields.map((f) => f.name);
+ const keys = new Set();
+ for (const row of data as Record[]) {
+ if (row && typeof row === "object") {
+ for (const key of Object.keys(row)) keys.add(key);
+ }
+ }
+ return Array.from(keys);
+}
+
+/**
+ * Returns a message naming the keys that are not in the data, or `null` when
+ * every given key exists. Empty data is never reported.
+ */
+export function unknownKeysMessage(
+ data: ChartData,
+ keys: Record,
+): string | null {
+ const available = availableKeys(data);
+ if (available.length === 0) return null;
+ const missing: string[] = [];
+ for (const [prop, value] of Object.entries(keys)) {
+ if (value === undefined) continue;
+ for (const key of Array.isArray(value) ? value : [value]) {
+ if (!available.includes(key)) missing.push(`${prop} "${key}"`);
+ }
+ }
+ if (missing.length === 0) return null;
+ return `Unknown ${missing.join(", ")}. Available keys: ${available.join(", ")}.`;
+}
+
+/** Extra normalization options. */
+export interface NormalizeOptions {
+ /** Overrides the x axis type inferred from the `xKey` values. */
+ xType?: XAxisType;
+ /** Keep missing measures as `null` (a gap) instead of 0. v3 default. */
+ keepNulls?: boolean;
+ /**
+ * Column whose values name the series in long rows (x, series, value). The
+ * rows are pivoted to one series per distinct value of this column.
+ */
+ seriesKey?: string;
+}
+
+/**
+ * Pivots long rows (one row per x and series) into wide rows with one column
+ * per series, in first-appearance order. Returns the wide rows and the series
+ * names, which become the y keys.
+ */
+/**
+ * The x column of a pivoted row. Series names become columns too, so x has a
+ * key no series can take (a series named like the x column would overwrite it).
+ */
+const PIVOT_X_KEY = "\u0000x";
+
+function pivotLongRows(
+ rows: Record[],
+ xKey: string,
+ seriesKey: string,
+ valueKey: string,
+): { rows: Record[]; seriesNames: string[] } {
+ const byX = new Map>();
+ const seriesNames: string[] = [];
+ const seen = new Set();
+ for (const row of rows) {
+ const x = row[xKey];
+ const xId = x instanceof Date ? x.getTime() : x;
+ const series = String(row[seriesKey] ?? "");
+ if (!seen.has(series)) {
+ seen.add(series);
+ seriesNames.push(series);
+ }
+ let wide = byX.get(xId);
+ if (!wide) {
+ // No prototype: a series named "__proto__" must become a column.
+ wide = Object.create(null) as Record;
+ wide[PIVOT_X_KEY] = x;
+ byX.set(xId, wide);
+ }
+ wide[series] = row[valueKey];
+ }
+ return { rows: Array.from(byX.values()), seriesNames };
+}
+
+const WEEKDAYS = [
+ ["mon", "monday"],
+ ["tue", "tues", "tuesday"],
+ ["wed", "wednesday"],
+ ["thu", "thur", "thurs", "thursday"],
+ ["fri", "friday"],
+ ["sat", "saturday"],
+ ["sun", "sunday"],
+];
+const MONTHS = [
+ ["jan", "january"],
+ ["feb", "february"],
+ ["mar", "march"],
+ ["apr", "april"],
+ ["may"],
+ ["jun", "june"],
+ ["jul", "july"],
+ ["aug", "august"],
+ ["sep", "sept", "september"],
+ ["oct", "october"],
+ ["nov", "november"],
+ ["dec", "december"],
+];
+
+/** Position of `value` in a list of named periods, or -1. */
+function periodIndex(names: string[][], value: string | number): number {
+ const key = String(value).trim().toLowerCase().replace(/\.$/, "");
+ return names.findIndex((forms) => forms.includes(key));
+}
+
+/**
+ * Heatmap axis order. `order` lists values to put first, in that order.
+ * Otherwise weekdays (Monday first) and month names are put in calendar
+ * order, numbers (such as hours) ascending and date strings chronologically;
+ * any other categories keep their first-appearance order.
+ */
+function orderHeatmapAxis(
+ values: (string | number)[],
+ order?: readonly (string | number)[],
+): (string | number)[] {
+ if (order?.length) {
+ const rank = new Map(order.map((v, i) => [String(v), i]));
+ const listed = values
+ .filter((v) => rank.has(String(v)))
+ .sort((a, b) => (rank.get(String(a)) ?? 0) - (rank.get(String(b)) ?? 0));
+ return [...listed, ...values.filter((v) => !rank.has(String(v)))];
+ }
+ for (const names of [WEEKDAYS, MONTHS]) {
+ if (values.length > 0 && values.every((v) => periodIndex(names, v) >= 0)) {
+ return [...values].sort(
+ (a, b) => periodIndex(names, a) - periodIndex(names, b),
+ );
+ }
+ }
+ if (values.length > 0 && values.every(isNumericValue)) {
+ return [...values].sort((a, b) => Number(a) - Number(b));
+ }
+ const times = values.map(toChronologicalValue);
+ if (
+ values.length > 0 &&
+ values.every((v) => typeof v === "string") &&
+ times.every((t) => t !== null)
+ ) {
+ return values
+ .map((v, i) => ({ v, t: times[i] as number }))
+ .sort((a, b) => a.t - b.t)
+ .map(({ v }) => v);
+ }
+ return values;
+}
+
+/**
+ * Labels for a missing and an empty category. Both used to be "", so two
+ * different rows got two blank labels and a click returned `name: ""`.
+ */
+export const NULL_X_LABEL = "(null)";
+const EMPTY_X_LABEL = "(empty)";
+
+/** Arrow x values: a missing value is labelled instead of turned into 0. */
+function arrowXValues(values: unknown[]): (string | number)[] {
+ return values.map((v) =>
+ v === null || v === undefined ? NULL_X_LABEL : toChartValue(v),
+ );
+}
+
+/** Column that names the spokes of a radar pivoted from entity rows. */
+export const RADAR_METRIC_KEY = "\u0000metric";
+
+/**
+ * Turns one row per entity (`name, speed, power, range`) into the one row
+ * per metric a radar draws (`metric, , `). The entity
+ * names, from `entityKey` (or the first text column), become the series.
+ */
+export function pivotRadarEntities(
+ data: ChartData,
+ entityKey: string | undefined,
+ metrics: readonly string[],
+): {
+ rows: Record[];
+ entities: string[];
+ entityRows: Record[];
+} {
+ const entityRows = (
+ isArrowTable(data) ? extractJsonFromArrow(data) : data
+ ) as Record[];
+ const first = entityRows[0] ?? {};
+ const key =
+ entityKey ??
+ Object.keys(first).find((k) => typeof first[k] === "string") ??
+ Object.keys(first)[0];
+ const entities = entityRows.map((row, i) =>
+ row[key] === null || row[key] === undefined
+ ? `Row ${i + 1}`
+ : String(row[key]),
+ );
+ const rows = metrics.map((metric) => {
+ const row: Record = { [RADAR_METRIC_KEY]: metric };
+ entityRows.forEach((entity, i) => {
+ row[entities[i]] = entity[metric];
+ });
+ return row;
+ });
+ return { rows, entities, entityRows };
+}
+
+/** Key that carries source row indices through the x sorts. */
+const ROW_INDEX_KEY = "\u0000row";
+
+/**
+ * Sorts a time axis chronologically and a numeric axis ascending; category
+ * values keep their row order and their text ("007" stays "007"). Also
+ * returns, for each x position, the index of its source row.
+ */
+function sortByXAxis(
+ xData: (string | number)[],
+ yDataMap: Record,
+ yFields: string[],
+ chartType: "timeseries" | "categorical",
+ xAxisType: XAxisType,
+): {
+ xData: (string | number)[];
+ yDataMap: Record;
+ rowIndex: number[];
+} {
+ if (xAxisType === "category") {
+ xData = xData.map((x) => (x === "" ? EMPTY_X_LABEL : x));
+ }
+ const tracked: Record = {
+ ...yDataMap,
+ [ROW_INDEX_KEY]: xData.map((_, i) => i),
+ };
+ const fields = [...yFields, ROW_INDEX_KEY];
+ let sorted = { xData, yDataMap: tracked };
+ if (chartType === "timeseries") {
+ // A row whose x is not a date (such as "TBD") can't be placed on a time
+ // axis. It used to break the line and stop the whole series from being
+ // sorted; it is now left out, with a warning, and the rest is sorted.
+ const keep = xData
+ .map((x, i) => (toChronologicalValue(x) === null ? -1 : i))
+ .filter((i) => i >= 0);
+ if (keep.length < xData.length) {
+ const bad = xData.find((x) => toChronologicalValue(x) === null);
+ console.warn(
+ `[appkit-ui] ${xData.length - keep.length} row(s) have an x value that is not a date (such as ${JSON.stringify(bad)}) and were left off the time axis.`,
+ );
+ const pick = (values: T[]) => keep.map((i) => values[i]);
+ const filtered: Record = {};
+ for (const field of fields) filtered[field] = pick(tracked[field]);
+ sorted = sortTimeSeriesAscending(pick(xData), filtered, fields);
+ } else {
+ sorted = sortTimeSeriesAscending(xData, tracked, fields);
+ }
+ } else if (
+ xAxisType === "value" &&
+ xData.length > 0 &&
+ xData.every(isNumericValue)
+ ) {
+ sorted = sortNumericAscending(xData, tracked, fields);
+ }
+ const { [ROW_INDEX_KEY]: rowIndex, ...rest } = sorted.yDataMap;
+ return {
+ xData: sorted.xData,
+ yDataMap: rest,
+ rowIndex: rowIndex as number[],
+ };
+}
+
+/** A DATE column: Arrow stores each day as UTC midnight, so it names a day and not an instant. */
+function isArrowDateField(table: Table, key: string): boolean {
+ const field = table.schema.fields.find((f) => f.name === key);
+ return field?.typeId === ARROW_TYPE_IDS.Date;
+}
+
+/**
+ * The local midnight of the day a DATE value names. UTC midnight is the
+ * previous evening west of UTC, so the day is read from its UTC fields, as
+ * toChronologicalValue reads DATE strings.
+ */
+function utcDayToLocalMidnight(ms: number): number {
+ const d = new Date(ms);
+ return new Date(
+ d.getUTCFullYear(),
+ d.getUTCMonth(),
+ d.getUTCDate(),
+ ).getTime();
+}
+
+function isArrowTemporalField(table: Table, key: string): boolean {
+ const field = table.schema.fields.find((f) => f.name === key);
+ if (!field) return false;
+ return getTypeIdSets().temporal.has(field.typeId);
+}
+
export function normalizeChartData(
data: ChartData,
xKey?: string,
yKey?: string | string[],
orientation?: Orientation,
+ opts: NormalizeOptions = {},
): NormalizedChartData {
+ if (opts.seriesKey) {
+ const seriesKey = opts.seriesKey;
+ const rows = (
+ isArrowTable(data) ? extractJsonFromArrow(data) : data
+ ) as Record[];
+ const rest = rows.map((row) => {
+ const { [seriesKey]: _series, ...others } = row;
+ return others;
+ });
+ const detected = detectFieldsFromJson(rest, orientation);
+ const { resolvedXKey, resolvedYKeys } = resolveKeys(
+ detected,
+ rest.length > 0 ? Object.keys(rest[0]) : [],
+ xKey,
+ yKey,
+ );
+ const pivot = pivotLongRows(
+ rows,
+ resolvedXKey,
+ seriesKey,
+ resolvedYKeys[0],
+ );
+ const pivoted = normalizeChartData(
+ pivot.rows,
+ PIVOT_X_KEY,
+ pivot.seriesNames,
+ orientation,
+ {
+ ...opts,
+ seriesKey: undefined,
+ },
+ );
+ // Row indices point at the pivoted rows, not the caller's rows.
+ return { ...pivoted, xField: resolvedXKey, rowIndex: undefined };
+ }
+
if (isArrowTable(data)) {
const table = data as Table;
- const detected = ArrowClient.detectFieldsFromArrow(table, orientation);
- const resolvedXKey = xKey ?? detected.xField;
- const resolvedYKeys = yKey
- ? Array.isArray(yKey)
- ? yKey
- : [yKey]
- : detected.yFields;
+ const detected = detectFieldsFromTable(table, orientation);
+ const { resolvedXKey, resolvedYKeys } = resolveKeys(
+ detected,
+ table.schema.fields.map((f) => f.name),
+ xKey,
+ yKey,
+ );
+ const keepNulls = opts.keepNulls === true;
+ // The x column always keeps its nulls, so a null x is labelled (null) and not 0.
+ // Y values still follow `keepNulls` through toChartArray below.
const { xData: rawXData, yDataMap: rawYDataMap } =
- ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys);
-
- let xData = toChartArray(rawXData);
- let yDataMap: Record = {};
+ ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys, {
+ keepNulls: true,
+ });
+
+ const xAxisType: XAxisType =
+ opts.xType ??
+ (isArrowTemporalField(table, resolvedXKey)
+ ? "time"
+ : inferXType(rawXData));
+ const chartType = xAxisType === "time" ? "timeseries" : "categorical";
+
+ let xData = arrowXValues(rawXData);
+ if (isArrowDateField(table, resolvedXKey)) {
+ xData = xData.map((x) =>
+ typeof x === "number" ? utcDayToLocalMidnight(x) : x,
+ );
+ }
+ let yDataMap: Record = {};
for (const key of resolvedYKeys) {
- yDataMap[key] = toChartArray(rawYDataMap[key] ?? []);
+ yDataMap[key] = toChartArray(rawYDataMap[key] ?? [], keepNulls);
}
- if (detected.chartType === "timeseries") {
- ({ xData, yDataMap } = sortTimeSeriesAscending(
- xData,
- yDataMap,
- resolvedYKeys,
- ));
- } else if (xData.length > 0 && xData.every(isNumericValue)) {
- ({ xData, yDataMap } = sortNumericAscending(
- xData,
- yDataMap,
- resolvedYKeys,
- ));
- }
+ let rowIndex: number[];
+ ({ xData, yDataMap, rowIndex } = sortByXAxis(
+ xData,
+ yDataMap,
+ resolvedYKeys,
+ chartType,
+ xAxisType,
+ ));
return {
+ rowIndex,
xData,
yDataMap,
xField: resolvedXKey,
yFields: resolvedYKeys,
- chartType: detected.chartType,
+ chartType,
+ xAxisType,
+ xDateOnly:
+ chartType === "timeseries" && isArrowDateField(table, resolvedXKey),
};
}
// JSON Array
const jsonData = data as Record[];
const detected = detectFieldsFromJson(jsonData, orientation);
- const resolvedXKey = xKey ?? detected.xField;
- const resolvedYKeys = yKey
- ? Array.isArray(yKey)
- ? yKey
- : [yKey]
- : detected.yFields;
+ const { resolvedXKey, resolvedYKeys } = resolveKeys(
+ detected,
+ jsonData.length > 0 ? Object.keys(jsonData[0]) : [],
+ xKey,
+ yKey,
+ );
+
+ const xAxisType: XAxisType =
+ opts.xType ?? inferXType(columnValues(jsonData, resolvedXKey));
+ const chartType = xAxisType === "time" ? "timeseries" : "categorical";
const { xData: rawXData, yDataMap: rawYDataMap } = extractFromJson(
jsonData,
resolvedXKey,
resolvedYKeys,
+ chartType === "timeseries",
+ opts.keepNulls === true,
);
let xData = toChartArray(rawXData);
- let yDataMap: Record = {};
+ let yDataMap: Record = {};
for (const key of resolvedYKeys) {
- yDataMap[key] = toChartArray(rawYDataMap[key] ?? []);
+ yDataMap[key] = toChartArray(
+ rawYDataMap[key] ?? [],
+ opts.keepNulls === true,
+ );
}
- if (detected.chartType === "timeseries") {
- ({ xData, yDataMap } = sortTimeSeriesAscending(
- xData,
- yDataMap,
- resolvedYKeys,
- ));
- } else if (xData.length > 0 && xData.every(isNumericValue)) {
- ({ xData, yDataMap } = sortNumericAscending(
- xData,
- yDataMap,
- resolvedYKeys,
- ));
- }
+ let rowIndex: number[];
+ ({ xData, yDataMap, rowIndex } = sortByXAxis(
+ xData,
+ yDataMap,
+ resolvedYKeys,
+ chartType,
+ xAxisType,
+ ));
return {
+ rowIndex,
xData,
yDataMap,
xField: resolvedXKey,
yFields: resolvedYKeys,
- chartType: detected.chartType,
+ chartType,
+ xAxisType,
+ xDateOnly:
+ chartType === "timeseries" &&
+ isDateOnlyColumn(columnValues(jsonData, resolvedXKey)),
};
}
@@ -327,6 +826,12 @@ export interface NormalizedHeatmapData extends NormalizedChartDataBase {
yAxisData: (string | number)[];
/** Heatmap data as [xIndex, yIndex, value] tuples */
heatmapData: [number, number, number][];
+ /** Source row index of each `heatmapData` cell. */
+ cellRowIndex: number[];
+ /** Every value of the value column is text, so nothing can be drawn. */
+ valueIsText?: boolean;
+ /** The row (y axis) column. */
+ yAxisField?: string;
/** Min value in the data */
min: number;
/** Max value in the data */
@@ -347,6 +852,11 @@ export function normalizeHeatmapData(
xKey?: string,
yAxisKey?: string,
valueKey?: string | string[],
+ opts: {
+ keepNulls?: boolean;
+ xOrder?: readonly (string | number)[];
+ yOrder?: readonly (string | number)[];
+ } = {},
): NormalizedHeatmapData {
// First, get the standard normalization
const jsonData = isArrowTable(data)
@@ -361,20 +871,28 @@ export function normalizeHeatmapData(
chartType: "categorical",
yAxisData: [],
heatmapData: [],
+ cellRowIndex: [],
min: 0,
max: 0,
};
}
// Detect fields if not provided
+ // A key not given is picked from the columns the others don't use: the
+ // value from the numeric ones, the column and row from the rest (it used to
+ // be columns 1, 2 and 3 by position).
const keys = Object.keys(jsonData[0]);
- const resolvedXKey = xKey ?? keys[0];
- const resolvedYAxisKey = yAxisKey ?? keys[1];
- const resolvedValueKey = valueKey
- ? Array.isArray(valueKey)
- ? valueKey[0]
- : valueKey
- : keys[2];
+ const firstRow = jsonData[0];
+ const givenValueKey = Array.isArray(valueKey) ? valueKey[0] : valueKey;
+ const taken = new Set([xKey, yAxisKey, givenValueKey].filter(Boolean));
+ const free = keys.filter((k) => !taken.has(k));
+ const isNumberColumn = (k: string) => isNumericValue(firstRow[k]);
+ const resolvedValueKey =
+ givenValueKey ?? free.find(isNumberColumn) ?? free[free.length - 1];
+ const dims = free.filter((k) => k !== resolvedValueKey);
+ const resolvedXKey = xKey ?? dims[0] ?? keys[0];
+ const resolvedYAxisKey =
+ yAxisKey ?? dims.find((k) => k !== resolvedXKey) ?? keys[1];
// Extract unique X and Y categories
const xSet = new Set();
@@ -387,8 +905,8 @@ export function normalizeHeatmapData(
ySet.add(yVal);
}
- const xData = Array.from(xSet);
- const yAxisData = Array.from(ySet);
+ const xData = orderHeatmapAxis(Array.from(xSet), opts.xOrder);
+ const yAxisData = orderHeatmapAxis(Array.from(ySet), opts.yOrder);
// Create index maps for fast lookup
const xIndexMap = new Map();
@@ -402,25 +920,68 @@ export function normalizeHeatmapData(
// Build heatmap data and track min/max
const heatmapData: [number, number, number][] = [];
+ const cellRowIndex: number[] = [];
+ const cellAt = new Map();
+ let repeated = 0;
+ const nonNumeric: unknown[] = [];
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
- for (const row of jsonData) {
+ for (const [rowIdx, row] of jsonData.entries()) {
const xVal = jsonValueToChartValue(row[resolvedXKey], false, false);
const yVal = jsonValueToChartValue(row[resolvedYAxisKey], false, false);
- const value = jsonValueToChartValue(row[resolvedValueKey], true, false);
+ const rawValue = row[resolvedValueKey];
+ // v3: a missing value is an empty cell, not a 0 that skews the scale.
+ if (opts.keepNulls && isMissing(rawValue)) continue;
+ const value = jsonValueToChartValue(rawValue, true, false);
const xIdx = xIndexMap.get(xVal);
const yIdx = yIndexMap.get(yVal);
- const numValue = typeof value === "number" ? value : 0;
+ let numValue: number;
+ if (typeof value === "number" && Number.isFinite(value)) {
+ numValue = value;
+ } else if (isMissing(rawValue)) {
+ numValue = 0;
+ } else {
+ // Text such as "high", booleans or "1,234.5" are not values: leave the
+ // cell empty instead of drawing 0 and dragging the color scale to 0.
+ nonNumeric.push(rawValue);
+ continue;
+ }
if (xIdx !== undefined && yIdx !== undefined) {
- heatmapData.push([xIdx, yIdx, numValue]);
- min = Math.min(min, numValue);
- max = Math.max(max, numValue);
+ // Repeated (x, y) pairs are summed into one cell instead of drawn on
+ // top of each other.
+ const cellKey = `${xIdx}:${yIdx}`;
+ const existing = cellAt.get(cellKey);
+ if (existing !== undefined) {
+ heatmapData[existing][2] += numValue;
+ repeated++;
+ } else {
+ cellAt.set(cellKey, heatmapData.length);
+ heatmapData.push([xIdx, yIdx, numValue]);
+ cellRowIndex.push(rowIdx);
+ }
}
}
+ const valueIsText = nonNumeric.length > 0 && heatmapData.length === 0;
+ if (nonNumeric.length > 0 && !valueIsText) {
+ console.warn(
+ `[appkit-ui] heatmap: ${nonNumeric.length} value(s) in "${resolvedValueKey}" are not numbers and were left empty (first: ${JSON.stringify(nonNumeric[0])}).`,
+ );
+ }
+
+ if (repeated > 0) {
+ console.warn(
+ `[appkit-ui] heatmap: ${repeated} row(s) repeat an existing (${resolvedXKey}, ${resolvedYAxisKey}) cell; their values were summed. Aggregate in SQL to choose another rule.`,
+ );
+ }
+ for (const [, , value] of heatmapData) {
+ min = Math.min(min, value);
+ max = Math.max(max, value);
+ }
+
// Handle edge case where no valid data was found
if (heatmapData.length === 0) {
min = 0;
@@ -434,8 +995,11 @@ export function normalizeHeatmapData(
chartType: "categorical",
yAxisData,
heatmapData,
+ cellRowIndex,
min,
max,
+ ...(valueIsText ? { valueIsText } : {}),
+ yAxisField: resolvedYAxisKey,
};
}
diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts
index 84b64e404..dd427609d 100644
--- a/packages/appkit-ui/src/react/charts/options.ts
+++ b/packages/appkit-ui/src/react/charts/options.ts
@@ -1,9 +1,20 @@
import { FALLBACK_UI_TOKENS } from "./constants";
-import type { ChartType, ChartUITokens, ChartValueFormatter } from "./types";
+import type {
+ ChartReferenceLine,
+ ChartSeriesConfig,
+ ChartType,
+ ChartUITokens,
+ ChartValue,
+ ChartValueFormatter,
+} from "./types";
import {
createTimeSeriesData,
escapeHtml,
+ formatCompactNumber,
formatLabel,
+ formatLocalDate,
+ formatTimeLabel,
+ toChronologicalValue,
truncateLabel,
} from "./utils";
@@ -13,7 +24,7 @@ import {
export interface OptionBuilderContext {
xData: (string | number)[];
- yDataMap: Record;
+ yDataMap: Record;
yFields: string[];
colors: string[];
title?: string;
@@ -21,13 +32,39 @@ export interface OptionBuilderContext {
xField?: string;
ui?: ChartUITokens;
valueFormatter?: ChartValueFormatter;
+ /** Formats value-axis ticks and color-scale labels. Falls back to `valueFormatter`. */
+ axisValueFormatter?: ChartValueFormatter;
+ /** Formats `showValues` labels. Falls back to `axisValueFormatter`. */
+ valueLabelFormatter?: ChartValueFormatter;
+ /** x holds timestamps drawn on a category axis (horizontal bars). */
+ xIsTime?: boolean;
+ /** x holds DATE values (no time of day). */
+ xDateOnly?: boolean;
+ /** Build with the `defaults="v3"` defaults. */
+ v3?: boolean;
+ /** Measured chart width in px, when known. Sizes axis labels. */
+ chartWidth?: number;
+ /** Measured chart height in px, when known. */
+ chartHeight?: number;
+ /** Target or reference lines at values of the value axis. */
+ referenceLines?: ChartReferenceLine[];
+ /** Add zoom (wheel/drag plus a slider) along the category or time axis. */
+ zoom?: boolean;
+ /** Label each bar (or scatter point) with its value. */
+ showValues?: boolean;
+ /** Per-`yKey` series type and value axis (combo charts). */
+ seriesConfig?: Record;
}
export interface CartesianContext extends OptionBuilderContext {
chartType: ChartType;
isTimeSeries: boolean;
+ /** Plot x on a numeric value axis (`xType="value"`). */
+ isValueX?: boolean;
stacked: boolean;
smooth: boolean;
+ /** Draw line/area across `null` values instead of leaving a gap. */
+ connectNulls?: boolean;
showSymbol: boolean;
symbolSize: number;
/**
@@ -49,7 +86,17 @@ function buildBaseOption(ctx: OptionBuilderContext): Record {
? {
text: ctx.title,
left: "center",
- textStyle: { color: ui.axisTitle },
+ textStyle: {
+ color: ui.axisTitle,
+ // A title wider than the card is cut with an ellipsis, not
+ // centred and clipped on both sides.
+ ...(ctx.chartWidth
+ ? {
+ width: Math.max(40, ctx.chartWidth - TITLE_SIDE_MARGIN * 2),
+ overflow: "truncate",
+ }
+ : {}),
+ },
}
: undefined,
color: ctx.colors,
@@ -76,10 +123,133 @@ function mergeAxisLabel(
};
}
-function legendTextStyle(ui: ChartUITokens) {
- return { textStyle: { color: ui.axisTitle } };
+/** Space kept free at each side of a title, in px. */
+const TITLE_SIDE_MARGIN = 16;
+
+/** Height a cartesian chart reserves above the plot for a title, in px. */
+const TITLE_BAND = 44;
+
+/** Share of the chart width the plot area of a vertical category axis gets. */
+const PLOT_WIDTH_SHARE = 0.8;
+/** Narrowest slot an upright category label gets before labels rotate. */
+const MIN_UPRIGHT_LABEL_WIDTH = 48;
+/** Pitch a 45 degree category label needs, in px. */
+const ROTATED_LABEL_PITCH = 18;
+/** Width a rotated category label is truncated to. */
+const ROTATED_LABEL_WIDTH = 90;
+
+/**
+ * Axis label settings for a category axis along x. With a measured chart
+ * width, every label is drawn and truncated (with an ellipsis) to the space it
+ * has, rotating when the slots get too narrow. Without one (server render,
+ * tests), labels are cut at a fixed character count as before.
+ */
+function categoryXAxisLabel(
+ ctx: OptionBuilderContext,
+ count: number,
+ fallbackChars: number,
+): Record {
+ if (!ctx.chartWidth || count === 0) {
+ return {
+ rotate: count > 10 ? 45 : 0,
+ formatter: (v: string) => truncateLabel(String(v), fallbackChars),
+ };
+ }
+ const slot = (ctx.chartWidth * PLOT_WIDTH_SHARE) / count;
+ if (slot >= MIN_UPRIGHT_LABEL_WIDTH) {
+ return { interval: 0, width: Math.floor(slot - 8), overflow: "truncate" };
+ }
+ return {
+ // "auto" does not know the rotation: draw every nth label, n from the
+ // pitch a 45 degree label needs.
+ interval:
+ slot >= ROTATED_LABEL_PITCH
+ ? 0
+ : Math.ceil(ROTATED_LABEL_PITCH / slot) - 1,
+ // Rotated labels need about 17 px a slot: past that, thin them out.
+ hideOverlap: true,
+ rotate: 45,
+ width: ROTATED_LABEL_WIDTH,
+ overflow: "truncate",
+ };
+}
+
+/** Approximate width of a formatted date label ("2026-01-05"), in px. */
+const DATE_LABEL_WIDTH = 72;
+/** The same with a time of day ("2026-01-05 13:00"). */
+const DATE_TIME_LABEL_WIDTH = 110;
+
+/**
+ * Labels of bars over dates (a category axis of formatted dates). When the
+ * slots are narrower than a date, every nth label is drawn, upright, instead
+ * of 730 rotated labels forming a solid band. Dates that fit use the regular
+ * category label settings.
+ */
+function dateBarXAxisLabel(
+ ctx: OptionBuilderContext,
+ count: number,
+): Record {
+ const regular = categoryXAxisLabel(ctx, count, 10);
+ if (!ctx.chartWidth || count === 0) return regular;
+ const labelWidth = ctx.xDateOnly ? DATE_LABEL_WIDTH : DATE_TIME_LABEL_WIDTH;
+ const slot = (ctx.chartWidth * PLOT_WIDTH_SHARE) / count;
+ if (slot >= labelWidth / 2) return regular;
+ return {
+ interval: Math.ceil(labelWidth / slot) - 1,
+ rotate: 0,
+ hideOverlap: true,
+ };
+}
+
+/** Pitch a 12 px row label needs, in px. */
+const ROW_LABEL_PITCH = 16;
+
+/**
+ * Every nth row label of a horizontal bar chart when the rows are closer than
+ * a label is tall (hideOverlap alone left them overprinted). Needs the
+ * measured height; the plot is the height minus about 56 px of margins.
+ */
+function rowLabelInterval(ctx: OptionBuilderContext): Record {
+ if (!ctx.chartHeight || ctx.xData.length === 0) return {};
+ const pitch = (ctx.chartHeight - 56) / ctx.xData.length;
+ return pitch >= ROW_LABEL_PITCH
+ ? {}
+ : { interval: Math.ceil(ROW_LABEL_PITCH / Math.max(pitch, 1)) - 1 };
}
+/** Width a category label along y (horizontal bars, heatmap rows) gets. */
+function categoryYLabelWidth(ctx: OptionBuilderContext): number {
+ if (!ctx.chartWidth) return 100;
+ return Math.round(Math.min(220, Math.max(60, ctx.chartWidth * 0.3)));
+}
+
+/**
+ * Series legend: one scrolling row, so many series never wrap over the axis
+ * labels (the old legend wrapped in a fixed 20% band).
+ */
+function seriesLegend(ui: ChartUITokens, ctx?: OptionBuilderContext) {
+ const width = ctx?.chartWidth;
+ return {
+ type: "scroll",
+ // Bounded width: the pager appears before the last item is cut, and one
+ // long series name is truncated instead of taking a whole page.
+ ...(width ? { width: Math.max(80, width - 48) } : {}),
+ textStyle: {
+ color: ui.axisTitle,
+ ...(width
+ ? {
+ width: Math.max(60, Math.floor(width * 0.35)),
+ overflow: "truncate",
+ }
+ : {}),
+ },
+ tooltip: { show: true },
+ };
+}
+
+/** Height reserved under a cartesian plot for the one-row legend, in px. */
+const LEGEND_BAND = 36;
+
function tooltipTokens(ui: ChartUITokens) {
return {
backgroundColor: ui.tooltipBg,
@@ -98,48 +268,218 @@ function toMeasureValue(value: unknown): string | number {
return scalar == null ? "" : String(scalar);
}
+interface AxisTooltipItem {
+ marker?: string;
+ seriesName?: string;
+ seriesIndex?: number;
+ value?: unknown;
+ axisValueLabel?: string;
+}
+
+/**
+ * Axis tooltip for a stack: one line per series and a total. `topFirst` lists
+ * the top band first, the order a vertical stack reads in (series 1 is the
+ * bottom band). The total adds up the stacked fields only: a line or area
+ * on the right axis (combo charts) is listed but not summed.
+ */
+function stackedTooltip(
+ ctx: OptionBuilderContext,
+ topFirst: boolean,
+ stackedFields: ReadonlySet,
+) {
+ return (params: unknown) => {
+ const items = (
+ Array.isArray(params) ? params : [params]
+ ) as AxisTooltipItem[];
+ const ordered = topFirst ? [...items].reverse() : items;
+ const format = (value: string | number, field: string | undefined) =>
+ ctx.valueFormatter && field
+ ? ctx.valueFormatter(value, field)
+ : String(value);
+ let total = 0;
+ const lines = ordered.map((item) => {
+ const value = toMeasureValue(item.value);
+ const n = Number(value);
+ const field = ctx.yFields[item.seriesIndex ?? 0];
+ if (value !== "" && Number.isFinite(n) && stackedFields.has(field)) {
+ total += n;
+ }
+ const text = value === "" ? "-" : format(value, field);
+ // `marker` is the series swatch, HTML built by ECharts.
+ return `${item.marker ?? ""}${escapeHtml(item.seriesName ?? "")}: ${escapeHtml(text)}`;
+ });
+ const head = escapeHtml(items[0]?.axisValueLabel ?? "");
+ // 0.1 + 0.2 + 1.1 is 1.4000000000000001: drop the float noise before the
+ // sum reaches a formatter that prints it as it is.
+ const exactTotal = Number(total.toPrecision(12));
+ const totalLine = `Total: ${escapeHtml(format(exactTotal, ctx.yFields[0]))}`;
+ return [head, ...lines, totalLine].join(" ");
+ };
+}
+
function tooltipValueFormatter(formatter: ChartValueFormatter, field: string) {
return (value: unknown) => formatter(toMeasureValue(value), field);
}
-function valueAxisLabel(ctx: OptionBuilderContext) {
- const field = ctx.yFields[0];
- const formatter = ctx.valueFormatter;
+function valueAxisLabel(
+ ctx: OptionBuilderContext,
+ field: string | undefined = ctx.yFields[0],
+) {
+ const formatter = ctx.axisValueFormatter ?? ctx.valueFormatter;
+ // A user valueFormatter prints full numbers ("$2,000,000"): ticks that
+ // would touch are hidden rather than run together.
return formatter && field
- ? { formatter: (value: string | number) => formatter(value, field) }
- : {};
+ ? {
+ hideOverlap: true,
+ formatter: (value: string | number) => formatter(value, field),
+ }
+ : { hideOverlap: true };
}
// ============================================================================
// Radar Chart Option
// ============================================================================
+/** Steps a radar rim rounds up to, times a power of ten. */
+const NICE_STEPS = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];
+/** Radar metrics whose largest values differ by more than this get their own scale. */
+const RADAR_MIXED_SCALE_RATIO = 10;
+
+/** The smallest "nice" number (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8 x 10^k) >= `value`. */
+function niceCeil(value: number): number {
+ if (!(value > 0)) return 1;
+ const magnitude = 10 ** Math.floor(Math.log10(value));
+ const step = NICE_STEPS.find((m) => m * magnitude >= value * (1 - 1e-9));
+ return (step ?? 10) * magnitude;
+}
+
+/**
+ * One rim value per radar spoke. Metrics on one scale share a rim (the
+ * largest value rounded up to a nice number, so scores out of 100 get 100,
+ * not 120). When the largest values of the metrics differ by more than 10x,
+ * each spoke gets its own rim, so small-scale metrics don't collapse to the
+ * centre.
+ */
+function radarAxisMaxima(ctx: OptionBuilderContext): number[] {
+ const perAxis = ctx.xData.map((_, i) =>
+ Math.max(0, ...ctx.yFields.map((f) => Number(ctx.yDataMap[f]?.[i]) || 0)),
+ );
+ const positive = perAxis.filter((v) => v > 0);
+ const mixed =
+ positive.length > 1 &&
+ Math.max(...positive) / Math.min(...positive) > RADAR_MIXED_SCALE_RATIO;
+ if (mixed) return perAxis.map(niceCeil);
+ const shared = niceCeil(Math.max(0, ...perAxis));
+ return perAxis.map(() => shared);
+}
+
+/** Smallest radius (px) at which a radar draws its default five rings. */
+const RADAR_FULL_RINGS_RADIUS = 110;
+
+/** Approximate width of one character of a spoke name, in px. */
+const RADAR_NAME_CHAR_WIDTH = 6.5;
+
+/**
+ * Spoke names and radius from the measured size: names get up to a quarter of
+ * the width and are truncated (with an ellipsis) past it, and the radius is
+ * what is left, so neither the names nor the polygon are cut off. Before the
+ * chart is measured, ECharts' default radius is kept.
+ */
+function radarLayout(ctx: OptionBuilderContext): Record {
+ const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
+ const { chartWidth: width, chartHeight: height } = ctx;
+ if (!width || !height) {
+ return { axisName: { color: ui.axisTitle } };
+ }
+ const longest = Math.max(0, ...ctx.xData.map((x) => String(x).length));
+ const nameWidth = Math.round(
+ Math.min(longest * RADAR_NAME_CHAR_WIDTH, width * 0.25),
+ );
+ const legendBand = ctx.showLegend && ctx.yFields.length > 1 ? 36 : 0;
+ const titleBand = ctx.title ? 32 : 0;
+ const radius = Math.max(
+ 30,
+ Math.min(
+ width / 2 - nameWidth - 12,
+ (height - legendBand - titleBand) / 2 - 22,
+ ),
+ );
+ return {
+ radius: Math.round(radius),
+ // Fewer rings on a small radar, so the 10 px ring values do not overlap
+ // (60/40/20 at 200 px); the top value also clears the top metric name.
+ splitNumber: radius >= RADAR_FULL_RINGS_RADIUS ? 5 : radius >= 50 ? 4 : 2,
+ nameGap: 20,
+ center: [
+ "50%",
+ Math.round(titleBand + (height - legendBand - titleBand) / 2),
+ ],
+ axisName: {
+ color: ui.axisTitle,
+ width: nameWidth,
+ overflow: "truncate",
+ // The width and overflow above are not applied to radar axis names, so
+ // the names still ran past the card edges: cut them here as well.
+ formatter: (name: string) =>
+ truncateLabel(
+ String(name),
+ Math.max(4, Math.floor(nameWidth / RADAR_NAME_CHAR_WIDTH) - 3),
+ ),
+ },
+ };
+}
+
export function buildRadarOption(
ctx: OptionBuilderContext,
showArea = true,
+ max?: number | readonly number[],
): Record {
const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
const formatter = ctx.valueFormatter;
- const maxValue = Math.max(
- ...ctx.yFields.flatMap((f) => ctx.yDataMap[f].map((v) => Number(v) || 0)),
- );
+ const dataMax = radarAxisMaxima(ctx);
+ const axisMax = dataMax.map((value, i) => {
+ const given = typeof max === "number" ? max : max?.[i];
+ return given !== undefined && Number.isFinite(given) && given > 0
+ ? given
+ : value;
+ });
+ // Ring values: on the first spoke when all spokes share a scale, on every
+ // spoke when they don't.
+ const sharedScale = axisMax.every((value) => value === axisMax[0]);
+ const ringFormatter = ctx.axisValueFormatter ?? formatter;
+ const field = ctx.yFields[0];
+ const ringLabel = {
+ show: true,
+ showMinLabel: false,
+ color: ui.axisLabel,
+ fontSize: 10,
+ ...(ringFormatter && field
+ ? { formatter: (value: number) => ringFormatter(value, field) }
+ : {}),
+ };
return {
...buildBaseOption(ctx),
tooltip: { ...tooltipTokens(ui), trigger: "item" },
legend:
ctx.showLegend && ctx.yFields.length > 1
- ? { top: "bottom", ...legendTextStyle(ui) }
+ ? { top: "bottom", ...seriesLegend(ui, ctx) }
: undefined,
radar: {
- indicator: ctx.xData.map((name) => ({
+ indicator: ctx.xData.map((name, i) => ({
name: String(name),
- max: maxValue * 1.2,
+ max: axisMax[i],
+ ...(i === 0 || !sharedScale ? { axisLabel: ringLabel } : {}),
})),
shape: "polygon",
- axisName: { color: ui.axisTitle },
+ ...radarLayout(ctx),
axisLine: { lineStyle: { color: ui.grid } },
splitLine: { lineStyle: { color: ui.grid } },
+ // Ring bands from the theme's grid color; ECharts' default light grey
+ // bands stayed light in the dark theme.
+ splitArea: {
+ areaStyle: { color: [ui.grid, "transparent"], opacity: 0.35 },
+ },
},
series: [
{
@@ -169,25 +509,334 @@ export function buildRadarOption(
// Pie/Donut Chart Option
// ============================================================================
+/** With `defaults="v3"`: most slices a pie draws before the tail becomes "Other". */
+const PIE_MAX_SLICES = 5;
+
+/** Outer radius of a pie, in percent of the chart's half-size. */
+const PIE_OUTER_RADIUS = 70;
+/** Largest hole, as a share of the outer radius. */
+const MAX_HOLE_SHARE = 0.9;
+
+/**
+ * The donut hole radius in percent, clamped to 0 up to 90% of the outer
+ * radius (it used to pass the outer radius from 70 up and overflow the card
+ * at 100). A DonutChart without `innerRadius` gets 40; `innerRadius={0}`
+ * means no hole.
+ */
+function pieHoleRadius(
+ chartType: "pie" | "donut",
+ innerRadius: number | undefined,
+): number {
+ const requested = innerRadius ?? (chartType === "donut" ? 40 : 0);
+ if (!Number.isFinite(requested) || requested <= 0) return 0;
+ return Math.min(requested, PIE_OUTER_RADIUS * MAX_HOLE_SHARE);
+}
+
+interface PieSlice {
+ name: string;
+ value: ChartValue;
+ /** x position of the slice; absent for the "Other" slice. */
+ sourceIndex?: number;
+}
+
+function sliceValue(slice: PieSlice): number {
+ const n = Number(slice.value);
+ return Number.isFinite(n) ? n : 0;
+}
+
+/**
+ * v3 slices: largest first, and past {@link PIE_MAX_SLICES} the smallest are
+ * summed into one "Other" slice (top 4 plus Other).
+ */
+function v3Slices(slices: PieSlice[]): PieSlice[] {
+ const sorted = [...slices].sort((a, b) => sliceValue(b) - sliceValue(a));
+ if (sorted.length <= PIE_MAX_SLICES) return sorted;
+ const head = sorted.slice(0, PIE_MAX_SLICES - 1);
+ const other = sorted
+ .slice(PIE_MAX_SLICES - 1)
+ .reduce((sum, slice) => sum + sliceValue(slice), 0);
+ return [...head, { name: "Other", value: other }];
+}
+
+/** Below this width (px) the pie legend moves under the pie. */
+const PIE_SIDE_LEGEND_MIN_WIDTH = 360;
+/** Share of the chart width a side legend may take. */
+const PIE_SIDE_LEGEND_SHARE = 0.3;
+
+/**
+ * Where the pie and its legend go. A side legend gets at most 30% of the
+ * width (names are truncated to fit) and the pie is centred in the rest; on a
+ * narrow or tall chart the legend goes underneath. Without a legend the pie is
+ * centred. Before the chart is measured, the old layout (legend left, pie at
+ * 60%) is kept, with names truncated at 120 px.
+ */
+function pieBaseLayout(ctx: OptionBuilderContext): {
+ center: [string, string];
+ legendAtBottom: boolean;
+ legendTextWidth: number;
+} {
+ const width = ctx.chartWidth;
+ const height = ctx.chartHeight;
+ if (!ctx.showLegend) {
+ return {
+ center: ["50%", "50%"],
+ legendAtBottom: false,
+ legendTextWidth: 0,
+ };
+ }
+ const narrow =
+ width !== undefined &&
+ (width < PIE_SIDE_LEGEND_MIN_WIDTH ||
+ (height !== undefined && width < height * 1.2));
+ if (ctx.v3 || narrow) {
+ return {
+ center: ["50%", "44%"],
+ legendAtBottom: true,
+ legendTextWidth: width ? Math.max(60, Math.floor(width * 0.4)) : 160,
+ };
+ }
+ if (width === undefined) {
+ return {
+ center: ["60%", "50%"],
+ legendAtBottom: false,
+ legendTextWidth: 120,
+ };
+ }
+ const legendWidth = Math.floor(width * PIE_SIDE_LEGEND_SHARE);
+ const centerX = (legendWidth + (width - legendWidth) / 2) / width;
+ return {
+ center: [`${Math.round(centerX * 100)}%`, "50%"],
+ legendAtBottom: false,
+ // Swatch and gap take about 30 px.
+ legendTextWidth: Math.max(40, legendWidth - 30),
+ };
+}
+
+/** Approximate width of a legend character, in px. */
+const LEGEND_CHAR_WIDTH = 7;
+/** Fewest characters of a name a pie legend keeps. */
+const MIN_LEGEND_NAME_CHARS = 6;
+
+/** Height a title takes above a pie, and a bottom legend takes below it, in px. */
+const PIE_TITLE_BAND = 40;
+const PIE_LEGEND_BAND = 32;
+
+interface PieLayout {
+ center: [string | number, string | number];
+ legendAtBottom: boolean;
+ legendTextWidth: number;
+ /** Factor (up to 1) the radii are scaled by to leave room for a title. */
+ radiusScale: number;
+}
+
+/**
+ * {@link pieBaseLayout} with a title: the pie is centred in the height left
+ * under the title (and above a bottom legend) and shrinks when that is less
+ * than the pie needs, so the title never sits on the pie or the ring.
+ */
+function pieLayout(ctx: OptionBuilderContext): PieLayout {
+ const base = pieBaseLayout(ctx);
+ const { chartWidth: width, chartHeight: height } = ctx;
+ if (!ctx.title || !width || !height) return { ...base, radiusScale: 1 };
+ const bottom = ctx.showLegend && base.legendAtBottom ? PIE_LEGEND_BAND : 0;
+ const available = height - PIE_TITLE_BAND - bottom;
+ const half = Math.min(width, height) / 2;
+ const wanted = (PIE_OUTER_RADIUS / 100) * half;
+ const radiusScale = Math.min(1, Math.max(0.3, (available / 2 - 6) / wanted));
+ return {
+ ...base,
+ center: [base.center[0], Math.round(PIE_TITLE_BAND + available / 2)],
+ radiusScale,
+ };
+}
+
+/** Largest and smallest font size of the donut hole text, in px. */
+const CENTER_FONT_MAX = 24;
+const CENTER_FONT_MIN = 11;
+/** Average glyph width as a share of the font size. */
+const GLYPH_WIDTH = 0.6;
+
+/** Line height of the smallest hole text, in px. */
+const CENTER_LINE_HEIGHT = 14;
+
+/**
+ * Breaks `text` at spaces into lines of at most `box` px at the smallest font
+ * size, as many lines as fit in `box` px; the last line ends in "..." when
+ * text is left over.
+ */
+function wrapCenterText(text: string, box: number): string {
+ const perLine = Math.max(
+ 4,
+ Math.floor(box / (CENTER_FONT_MIN * GLYPH_WIDTH)),
+ );
+ const maxLines = Math.max(1, Math.floor(box / CENTER_LINE_HEIGHT));
+ const lines: string[] = [];
+ let line = "";
+ for (const word of text.split(/\s+/).filter(Boolean)) {
+ const next = line ? `${line} ${word}` : word;
+ if (next.length <= perLine || !line) {
+ line = next;
+ } else {
+ lines.push(line);
+ line = word;
+ }
+ }
+ if (line) lines.push(line);
+ // Each line is cut once: a word longer than a line, or the last line when
+ // text is left over, ends in a single "...".
+ const shown = lines.slice(0, maxLines);
+ return shown
+ .map((l, i) => {
+ const leftOver = i === shown.length - 1 && lines.length > maxLines;
+ return leftOver || l.length > perLine
+ ? `${l.slice(0, perLine - 3)}...`
+ : l;
+ })
+ .join("\n");
+}
+
+/**
+ * Fits the donut hole text: the font shrinks with the hole and the text
+ * length, and a total that still doesn't fit is compacted ("9.7M"). Before the
+ * chart is measured, totals of 7 or more characters are compacted.
+ */
+function centerFit(
+ content: { total: number; full: string } | { text: string } | undefined,
+ hole: number,
+ ctx: OptionBuilderContext,
+): { text: string; fontSize: number } | undefined {
+ if (!content) return undefined;
+ const side =
+ ctx.chartWidth && ctx.chartHeight
+ ? Math.min(ctx.chartWidth, ctx.chartHeight)
+ : undefined;
+ // ECharts radius percentages are of half the smaller side.
+ const holeWidth = side ? (hole / 100) * side * 0.85 : undefined;
+ const fontFor = (text: string) =>
+ holeWidth
+ ? Math.min(
+ CENTER_FONT_MAX,
+ Math.floor(holeWidth / (Math.max(1, text.length) * GLYPH_WIDTH)),
+ )
+ : 20;
+ if ("text" in content) {
+ // Text that does not fit even at the smallest font is wrapped inside the
+ // square that fits the hole and cut with an ellipsis past it, instead of
+ // running over the ring.
+ const fits = !holeWidth || fontFor(content.text) >= CENTER_FONT_MIN;
+ return {
+ text:
+ fits || !side
+ ? content.text
+ : wrapCenterText(content.text, Math.floor((hole / 100) * side * 0.7)),
+ fontSize: Math.max(CENTER_FONT_MIN, fontFor(content.text)),
+ };
+ }
+ let text = content.full;
+ const tooLong = holeWidth
+ ? fontFor(text) < CENTER_FONT_MIN
+ : text.length >= 7;
+ if (tooLong) text = formatCompactNumber(content.total);
+ return { text, fontSize: Math.max(CENTER_FONT_MIN, fontFor(text)) };
+}
+
+/** Pie or donut extras beyond the shared props. */
+interface PieOptionExtras {
+ /** Text in the donut hole; `true` shows the formatted total. */
+ centerLabel?: string | boolean;
+}
+
export function buildPieOption(
ctx: OptionBuilderContext,
chartType: "pie" | "donut",
- innerRadius: number,
+ innerRadius: number | undefined,
showLabels: boolean,
labelPosition: string,
+ extras: PieOptionExtras = {},
): Record {
const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
- const pieData = ctx.xData.map((name, i) => ({
+ const valueField = ctx.yFields[0];
+ // `sourceIndex` maps a clicked slice back to its x position.
+ const rawSlices: PieSlice[] = ctx.xData.map((name, i) => ({
name: String(name),
- value: ctx.yDataMap[ctx.yFields[0]]?.[i] ?? 0,
+ value: ctx.yDataMap[valueField]?.[i] ?? 0,
+ sourceIndex: i,
}));
+ // Zero and missing values have no share: drawing them (as a 3-degree sliver
+ // labelled "0%") misstates the data.
+ const drawn = rawSlices.filter((slice) => sliceValue(slice) > 0);
+ const pieData = ctx.v3 ? v3Slices(drawn) : drawn;
- const isDonut = chartType === "donut" || innerRadius > 0;
- const valueField = ctx.yFields[0];
+ const layout = pieLayout(ctx);
+ // Outside labels (v3) get room: a smaller pie, and labels that align to the
+ // card edges and use all the space there.
+ const outsideLabels = ctx.v3 && showLabels && labelPosition === "outside";
+ const radiusScale = layout.radiusScale * (outsideLabels ? 0.85 : 1);
+ const hole = pieHoleRadius(chartType, innerRadius);
+ const isDonut = hole > 0;
const formatter = ctx.valueFormatter;
+ const shortFormatter = ctx.axisValueFormatter ?? formatter;
+ const total = pieData.reduce((sum, slice) => sum + sliceValue(slice), 0);
+ const formatValue = (value: number) =>
+ shortFormatter && valueField
+ ? shortFormatter(value, valueField)
+ : String(value);
+
+ // v3: the legend carries name, value and share; slice labels are off.
+ const values = new Map(pieData.map((slice) => [slice.name, slice]));
+ const v3LegendFormatter = (name: string) => {
+ const slice = values.get(name);
+ if (!slice || total === 0) return name;
+ const share = Math.round((sliceValue(slice) / total) * 1000) / 10;
+ const stats = ` ${formatValue(sliceValue(slice))} ${share}%`;
+ // Truncate the name, not the whole string: the value and share are the
+ // reason the legend exists. About 7 px a character, "..." included.
+ const chars = Math.floor(layout.legendTextWidth / LEGEND_CHAR_WIDTH);
+ const budget = Math.max(MIN_LEGEND_NAME_CHARS, chars - stats.length - 3);
+ return `${truncateLabel(name, budget)}${stats}`;
+ };
+
+ const centerLabel =
+ extras.centerLabel ?? (ctx.v3 && chartType === "donut" ? true : undefined);
+ const center = centerFit(
+ isDonut && centerLabel
+ ? centerLabel === true
+ ? { total, full: formatValue(total) }
+ : { text: centerLabel }
+ : undefined,
+ hole * radiusScale,
+ ctx,
+ );
+ const centerText = center?.text;
+
+ const base = buildBaseOption(ctx);
return {
- ...buildBaseOption(ctx),
+ ...base,
+ ...(centerText !== undefined
+ ? {
+ title: [
+ ...(base.title ? [base.title] : []),
+ {
+ text: centerText,
+ left: layout.center[0],
+ top: layout.center[1],
+ textAlign: "center",
+ textVerticalAlign: "middle",
+ textStyle: {
+ color: ui.axisTitle,
+ fontSize: center?.fontSize,
+ fontWeight: 600,
+ // Wrapped lines need a line height of their own, or they
+ // print over each other.
+ ...(centerText.includes("\n")
+ ? { lineHeight: CENTER_LINE_HEIGHT }
+ : {}),
+ },
+ },
+ ],
+ }
+ : {}),
tooltip: {
...tooltipTokens(ui),
trigger: "item",
@@ -205,30 +854,54 @@ export function buildPieOption(
},
legend: ctx.showLegend
? {
- orient: "vertical",
- left: "left",
- top: "middle",
- ...legendTextStyle(ui),
+ type: "scroll",
+ ...(layout.legendAtBottom
+ ? { orient: "horizontal", left: "center", bottom: 0 }
+ : { orient: "vertical", left: 0, top: "middle" }),
+ ...(ctx.v3 ? { formatter: v3LegendFormatter } : {}),
+ textStyle: {
+ color: ui.axisTitle,
+ width: layout.legendTextWidth,
+ overflow: "truncate",
+ },
+ tooltip: { show: true },
+ // Hiding a slice used to rescale the rest to a full circle with no
+ // sign that a part was missing.
+ selectedMode: false,
}
: undefined,
series: [
{
type: "pie",
- radius: isDonut ? [`${innerRadius || 40}%`, "70%"] : "70%",
- center: ["60%", "50%"],
- // Keep very small categories pointer-selectable. ECharts still reports
- // labels/tooltips from the true values, while a three-degree sector is
- // wide enough to survive CSS-pixel rounding on typical card sizes.
- minAngle: 3,
+ ...(valueField ? { name: formatLabel(valueField) } : {}),
+ radius: isDonut
+ ? [`${hole * radiusScale}%`, `${PIE_OUTER_RADIUS * radiusScale}%`]
+ : `${PIE_OUTER_RADIUS * radiusScale}%`,
+ center: layout.center,
data: pieData,
+ ...(outsideLabels ? { labelLayout: { hideOverlap: true } } : {}),
+ // Inside labels in the slice color vanished on their own slice; they
+ // are white with a dark outline. "center" used to draw only the first
+ // slice's label in the middle; it now shows the hovered slice.
label: {
- show: showLabels,
+ show: showLabels && labelPosition !== "center",
position: labelPosition,
formatter: "{b}: {d}%",
- color: "inherit",
- textBorderWidth: 0,
+ ...(outsideLabels
+ ? { alignTo: "edge", edgeDistance: 8, minMargin: 4 }
+ : {}),
+ ...(labelPosition === "inside"
+ ? {
+ color: "#fff",
+ textBorderColor: "rgba(0, 0, 0, 0.45)",
+ textBorderWidth: 2,
+ }
+ : { color: "inherit", textBorderWidth: 0 }),
},
emphasis: {
+ ...(showLabels && labelPosition === "center"
+ ? { label: { show: true, fontWeight: 600 } }
+ : {}),
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
@@ -250,6 +923,17 @@ export function buildHorizontalBarOption(
): Record {
const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
const hasMultipleSeries = ctx.yFields.length > 1;
+ // `series` config: the "right" value axis is drawn along the top.
+ const topFields = ctx.yFields.filter(
+ (f) => ctx.seriesConfig?.[f]?.axis === "right",
+ );
+ const bottomFields = ctx.yFields.filter((f) => !topFields.includes(f));
+ const bottomAxis = {
+ type: "value",
+ ...valueSplitNumber(ctx),
+ ...mergeAxisLabel(ui, valueAxisLabel(ctx, bottomFields[0])),
+ ...referenceAxisRange(ctx, true),
+ };
return {
...buildBaseOption(ctx),
@@ -257,40 +941,117 @@ export function buildHorizontalBarOption(
...tooltipTokens(ui),
trigger: "axis",
axisPointer: { type: "shadow" },
+ ...(stacked && hasMultipleSeries
+ ? { formatter: stackedTooltip(ctx, false, new Set(ctx.yFields)) }
+ : {}),
},
legend:
ctx.showLegend && hasMultipleSeries
- ? { top: "bottom", ...legendTextStyle(ui) }
+ ? { top: "bottom", ...seriesLegend(ui, ctx) }
: undefined,
+ ...(ctx.zoom ? { dataZoom: zoomComponents("y") } : {}),
+ // Pixel margins, with the label space reserved by containLabel: the old
+ // fixed 20% left and 5% bottom clipped long labels and the value ticks.
grid: {
- left: "20%",
- right: "10%",
- top: ctx.title ? "15%" : "5%",
- bottom: ctx.showLegend && hasMultipleSeries ? "15%" : "5%",
+ left: 8,
+ right:
+ Math.max(24, stacked ? 0 : valueLabelWidth(ctx)) +
+ (ctx.zoom ? ZOOM_SLIDER_SIZE + 8 : 0),
+ top: (ctx.title ? TITLE_BAND : 12) + (topFields.length ? 12 : 0),
+ bottom: ctx.showLegend && hasMultipleSeries ? 40 : 8,
+ containLabel: true,
},
- xAxis: { type: "value", ...mergeAxisLabel(ui, valueAxisLabel(ctx)) },
+ xAxis: topFields.length
+ ? [
+ bottomAxis,
+ {
+ type: "value",
+ position: "top",
+ ...mergeAxisLabel(ui, valueAxisLabel(ctx, topFields[0])),
+ splitLine: { show: false },
+ },
+ ]
+ : bottomAxis,
yAxis: {
type: "category",
data: ctx.xData,
+ // v3: the first row is the top bar, so `ORDER BY value DESC` reads
+ // largest first.
+ ...(ctx.v3 ? { inverse: true } : {}),
...mergeAxisLabel(ui, {
- width: 100,
+ width: categoryYLabelWidth(ctx),
overflow: "truncate",
- formatter: (value: string) => truncateLabel(String(value)),
+ // About 30 rows in 360 px leave 11 px a 12 px label: drop the ones
+ // that would overlap.
+ hideOverlap: true,
+ ...rowLabelInterval(ctx),
+ // With a measured width ECharts truncates to `width`; otherwise cut
+ // at a character count.
+ ...(ctx.xIsTime
+ ? {
+ formatter: (value: string) =>
+ formatTimeLabel(Number(value), ctx.xDateOnly === true),
+ }
+ : ctx.chartWidth
+ ? {}
+ : { formatter: (value: string) => truncateLabel(String(value)) }),
}),
- },
- series: ctx.yFields.map((key, idx) => ({
- name: formatLabel(key),
- type: "bar",
- data: ctx.yDataMap[key],
- stack: stacked ? "total" : undefined,
- itemStyle: { borderRadius: [0, 4, 4, 0] },
- color: ctx.colors[idx % ctx.colors.length],
- tooltip: ctx.valueFormatter
+ // Dates on a category axis: format the tooltip header the same way.
+ ...(ctx.xIsTime
? {
- valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key),
+ axisPointer: {
+ label: {
+ formatter: (params: { value: string | number }) =>
+ formatTimeLabel(Number(params.value), ctx.xDateOnly === true),
+ },
+ },
}
- : undefined,
- })),
+ : {}),
+ },
+ series: withReferenceLines(
+ roundBarEnds(
+ ctx.yFields.map((key, idx) => {
+ // Combo series (`series` prop) were ignored here: a line or area
+ // series was drawn as a second bar on the first value axis.
+ const config = ctx.seriesConfig?.[key];
+ const own = config?.type ?? "bar";
+ const ownLineLike = own === "line" || own === "area";
+ return {
+ name: formatLabel(key),
+ type: own === "area" ? "line" : own,
+ ...(config?.axis === "right" ? { xAxisIndex: 1 } : {}),
+ data:
+ ownLineLike || stacked
+ ? ctx.yDataMap[key]
+ : withSignedLabels(ctx, ctx.yDataMap[key], "left"),
+ stack:
+ stacked && !ownLineLike
+ ? ctx.seriesConfig
+ ? `bar-${config?.axis ?? "left"}`
+ : "total"
+ : undefined,
+ ...(own === "area" ? { areaStyle: { opacity: 0.3 } } : {}),
+ label: ownLineLike
+ ? undefined
+ : valueLabel(ctx, key, stacked ? "inside" : "right"),
+ ...valueLabelLayout(ctx, !ownLineLike),
+ itemStyle: ownLineLike ? undefined : { borderRadius: [0, 4, 4, 0] },
+ color: ctx.colors[idx % ctx.colors.length],
+ tooltip: ctx.valueFormatter
+ ? {
+ valueFormatter: tooltipValueFormatter(
+ ctx.valueFormatter,
+ key,
+ ),
+ }
+ : undefined,
+ };
+ }),
+ true,
+ ),
+ ctx,
+ "xAxis",
+ ),
};
}
@@ -307,8 +1068,34 @@ export interface HeatmapContext extends OptionBuilderContext {
min: number;
/** Max value for color scale */
max: number;
- /** Show value labels on cells */
- showLabels: boolean;
+ /** Show value labels on cells. Unset: only when they fit (see {@link heatmapLabelsFit}). */
+ showLabels?: boolean;
+}
+
+/** Width of the heatmap color scale bar, in px. */
+const SCALE_BAR_WIDTH = 14;
+/** Approximate width of one character of a scale label, in px. */
+const SCALE_CHAR_WIDTH = 7;
+
+/** Most cells a heatmap labels by default. */
+const HEATMAP_MAX_LABELLED_CELLS = 100;
+/** Narrowest cell that gets a label, in px. */
+const HEATMAP_MIN_LABEL_CELL_WIDTH = 32;
+
+/**
+ * Default for heatmap cell labels: on for up to 100 cells, when each cell is
+ * at least 32 px wide (measured), or there are at most 12 columns (before the
+ * chart is measured). Labels used to be on always and printed over each other
+ * past about ten columns.
+ */
+function heatmapLabelsFit(ctx: HeatmapContext): boolean {
+ const columns = ctx.xData.length;
+ if (columns * ctx.yAxisData.length > HEATMAP_MAX_LABELLED_CELLS) return false;
+ if (ctx.chartWidth) {
+ // The plot gets about 70% of the width (grid left and right 15%).
+ return (ctx.chartWidth * 0.7) / columns >= HEATMAP_MIN_LABEL_CELL_WIDTH;
+ }
+ return columns <= 12;
}
export function buildHeatmapOption(
@@ -317,8 +1104,19 @@ export function buildHeatmapOption(
const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
const valueField = ctx.yFields[0];
const formatter = ctx.valueFormatter;
+ const axisFormatter = ctx.axisValueFormatter ?? formatter;
const formatHeatmapValue = (value: number) =>
formatter && valueField ? formatter(value, valueField) : String(value);
+ const formatScaleValue = (value: number) =>
+ axisFormatter && valueField
+ ? axisFormatter(value, valueField)
+ : String(value);
+ // The color scale bar plus its widest end label.
+ const scaleLabel = Math.max(
+ formatScaleValue(ctx.min).length,
+ formatScaleValue(ctx.max).length,
+ );
+ const scaleWidth = SCALE_BAR_WIDTH + 8 + scaleLabel * SCALE_CHAR_WIDTH;
return {
...buildBaseOption(ctx),
tooltip: {
@@ -334,39 +1132,49 @@ export function buildHeatmapOption(
},
},
grid: {
- left: "15%",
- right: "15%",
- top: ctx.title ? "15%" : "10%",
- bottom: "15%",
+ // Pixel margins with the label space reserved by containLabel; the
+ // right margin holds the color scale and its widest label.
+ left: 8,
+ right: ctx.showLegend ? scaleWidth + 16 : 16,
+ top: ctx.title ? 40 : 12,
+ bottom: 8,
+ containLabel: true,
},
xAxis: {
type: "category",
data: ctx.xData,
splitArea: { show: true },
- ...mergeAxisLabel(ui, {
- rotate: ctx.xData.length > 10 ? 45 : 0,
- formatter: (v: string) => truncateLabel(String(v), 10),
- }),
+ ...mergeAxisLabel(ui, categoryXAxisLabel(ctx, ctx.xData.length, 10)),
},
yAxis: {
type: "category",
data: ctx.yAxisData,
splitArea: { show: true },
- ...mergeAxisLabel(ui, {
- formatter: (v: string) => truncateLabel(String(v), 12),
- }),
+ ...mergeAxisLabel(
+ ui,
+ ctx.chartWidth
+ ? { width: categoryYLabelWidth(ctx), overflow: "truncate" }
+ : { formatter: (v: string) => truncateLabel(String(v), 12) },
+ ),
},
visualMap: {
min: ctx.min,
max: ctx.max,
- calculable: true,
+ // Drag handles filtered cells out of the chart; off by default.
+ calculable: false,
+ // showLegend hides the scale; the colors still apply.
+ show: ctx.showLegend,
orient: "vertical",
- right: "2%",
+ right: 4,
top: "center",
+ itemWidth: SCALE_BAR_WIDTH,
textStyle: { color: ui.axisTitle },
+ // `calculable: false` also removed the handle labels, so the scale had
+ // no numbers: print the largest and smallest value at its ends.
+ text: [formatScaleValue(ctx.max), formatScaleValue(ctx.min)],
formatter:
- formatter && valueField
- ? (value: number) => formatter(value, valueField)
+ axisFormatter && valueField
+ ? (value: number) => axisFormatter(value, valueField)
: undefined,
inRange: {
// A visualMap gradient needs at least two stops; with a single-color
@@ -378,9 +1186,10 @@ export function buildHeatmapOption(
series: [
{
type: "heatmap",
+ ...(valueField ? { name: formatLabel(valueField) } : {}),
data: ctx.heatmapData,
label: {
- show: ctx.showLabels,
+ show: ctx.showLabels ?? heatmapLabelsFit(ctx),
formatter: (params: { data: [number, number, number] }) =>
formatHeatmapValue(params.data[2]),
},
@@ -399,6 +1208,484 @@ export function buildHeatmapOption(
// Cartesian Chart Option (line, bar, area, scatter)
// ============================================================================
+/** A finite number from a number or numeric string, else `null`. */
+function toFiniteNumber(value: unknown): number | null {
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+/**
+ * Scatter points: a point is dropped when either value is missing or not a
+ * number, so null, empty and text values are all handled the same way.
+ */
+/** Scatter tooltip: the series name, then both fields with their values. */
+function scatterTooltip(ctx: OptionBuilderContext, xIsTime = false) {
+ const xField = ctx.xField ?? "x";
+ const format = (value: unknown, field: string) => {
+ if (xIsTime && field === xField && typeof value === "number") {
+ return formatTimeLabel(value, ctx.xDateOnly === true);
+ }
+ const v =
+ typeof value === "number" || typeof value === "string" ? value : "";
+ return ctx.valueFormatter ? ctx.valueFormatter(v, field) : String(v);
+ };
+ return (params: {
+ seriesName?: string;
+ value?: unknown;
+ seriesIndex?: number;
+ }) => {
+ const [x, y] = Array.isArray(params.value) ? params.value : [];
+ const yField = ctx.yFields[params.seriesIndex ?? 0] ?? "y";
+ const rows = [
+ `${escapeHtml(formatLabel(xField))}: ${escapeHtml(format(x, xField))}`,
+ `${escapeHtml(formatLabel(yField))}: ${escapeHtml(format(y, yField))}`,
+ ];
+ const head =
+ ctx.yFields.length > 1 && params.seriesName
+ ? `${escapeHtml(params.seriesName)} `
+ : "";
+ return head + rows.join(" ");
+ };
+}
+
+/** Room under a scatter plot's x ticks for the axis name, in px. */
+const SCATTER_X_NAME_BAND = 40;
+
+/** Largest |x| from which scatter x ticks are compacted. */
+const SCATTER_COMPACT_X_MIN = 10000;
+
+/** Smallest scatter point drawn, in px. */
+const MIN_SCATTER_SYMBOL = 2;
+
+/** Point opacity for a scatter with `count` points. */
+function scatterOpacity(count: number): number {
+ if (count <= 50) return 0.8;
+ if (count <= 500) return 0.6;
+ if (count <= 5000) return 0.35;
+ return 0.2;
+}
+
+/** Positions in `xData` that become scatter points (both values numbers). */
+export function scatterPointIndices(
+ xData: (string | number)[],
+ yData: readonly ChartValue[],
+): number[] {
+ const indices: number[] = [];
+ for (let i = 0; i < xData.length; i++) {
+ if (toFiniteNumber(xData[i]) !== null && toFiniteNumber(yData[i]) !== null)
+ indices.push(i);
+ }
+ return indices;
+}
+
+function scatterPoints(
+ xData: (string | number)[],
+ yData: ChartValue[],
+): [number, number][] {
+ return scatterPointIndices(xData, yData).map((i) => [
+ toFiniteNumber(xData[i]) as number,
+ toFiniteNumber(yData[i]) as number,
+ ]);
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const HOUR_MS = 60 * 60 * 1000;
+/** Widest a bar gets when the chart has a single category. */
+const SINGLE_BAR_MAX_WIDTH = 80;
+
+/** Number of present (non-null) values in a series. */
+function countValues(values: readonly ChartValue[] | undefined): number {
+ return values ? values.filter((v) => v !== null && v !== "").length : 0;
+}
+
+/** Time axis bounds around a single x value, padded by the data grain. */
+function singleDateRange(
+ timestamp: number,
+ dateOnly: boolean,
+): { min: number; max: number } {
+ const pad = dateOnly ? DAY_MS : HOUR_MS;
+ return { min: timestamp - pad, max: timestamp + pad };
+}
+
+/**
+ * Series `label` that prints each mark's value, formatted like the value axis.
+ * Stacked bars put it inside the segment.
+ */
+function valueLabel(
+ ctx: OptionBuilderContext,
+ field: string,
+ position: "top" | "right" | "inside",
+): Record | undefined {
+ if (!ctx.showValues) return undefined;
+ const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
+ const format =
+ ctx.valueLabelFormatter ?? ctx.axisValueFormatter ?? ctx.valueFormatter;
+ return {
+ show: true,
+ position,
+ color: position === "inside" ? undefined : ui.axisLabel,
+ formatter: (params: { value: unknown }) => {
+ const value = toMeasureValue(params.value);
+ return format && value !== "" ? format(value, field) : String(value);
+ },
+ };
+}
+
+/**
+ * Series `labelLayout` for value labels: a label that would overlap another
+ * is hidden, so dense, grouped and stacked bars stay readable.
+ */
+function valueLabelLayout(
+ ctx: OptionBuilderContext,
+ shown: boolean,
+): Record {
+ return ctx.showValues && shown ? { labelLayout: { hideOverlap: true } } : {};
+}
+
+/**
+ * Bar data where a negative value's label sits at its far end (`below`), not
+ * on the zero line where it lands on the neighbouring bar's label. Stacked
+ * labels sit inside their segment and need no change.
+ */
+function withSignedLabels(
+ ctx: OptionBuilderContext,
+ data: ChartValue[],
+ below: "bottom" | "left",
+): ChartValue[] {
+ if (!ctx.showValues) return data;
+ return data.map((value) =>
+ toFiniteNumber(value) !== null && (toFiniteNumber(value) as number) < 0
+ ? ({ value, label: { position: below } } as unknown as ChartValue)
+ : value,
+ );
+}
+
+/**
+ * Fewer ticks on a narrow horizontal value axis, from the width of the widest
+ * formatted value, so full-number labels ("$2,000,000") are not left with one
+ * tick by hideOverlap. Wide enough charts keep ECharts' default.
+ */
+function valueSplitNumber(ctx: OptionBuilderContext): Record {
+ if (!ctx.chartWidth) return {};
+ const format = ctx.axisValueFormatter ?? ctx.valueFormatter;
+ let widest = 0;
+ for (const field of ctx.yFields) {
+ for (const value of ctx.yDataMap[field] ?? []) {
+ if (value === null || value === "") continue;
+ const text = format ? format(value, field) : String(value);
+ widest = Math.max(widest, text.length);
+ }
+ }
+ const plot = ctx.chartWidth - categoryYLabelWidth(ctx) - 32;
+ const fit = Math.floor(plot / (widest * VALUE_LABEL_CHAR_WIDTH + 16));
+ return fit < 5 ? { splitNumber: Math.max(2, fit) } : {};
+}
+
+/** Approximate width of one character of a value label, in px. */
+const VALUE_LABEL_CHAR_WIDTH = 7;
+
+/**
+ * Width the widest value label of the unstacked bars needs, so the label of
+ * the longest horizontal bar does not run off the canvas (`containLabel` does
+ * not count series labels).
+ */
+function valueLabelWidth(ctx: OptionBuilderContext): number {
+ if (!ctx.showValues) return 0;
+ const format =
+ ctx.valueLabelFormatter ?? ctx.axisValueFormatter ?? ctx.valueFormatter;
+ let chars = 0;
+ for (const field of ctx.yFields) {
+ for (const value of ctx.yDataMap[field] ?? []) {
+ if (value === null || value === "") continue;
+ const text = format ? format(value, field) : String(value);
+ chars = Math.max(chars, text.length);
+ }
+ }
+ return chars * VALUE_LABEL_CHAR_WIDTH + 8;
+}
+
+/** Height (or width, on horizontal bars) of the zoom slider, in px. */
+const ZOOM_SLIDER_SIZE = 18;
+
+/**
+ * Zoom components for the category or time axis: wheel and drag inside the
+ * plot, plus a slider along the bottom (or the right edge of horizontal bars).
+ */
+function zoomComponents(axis: "x" | "y"): Record[] {
+ const axisIndex = axis === "x" ? { xAxisIndex: 0 } : { yAxisIndex: 0 };
+ const slider =
+ axis === "x"
+ ? { bottom: 4, height: ZOOM_SLIDER_SIZE }
+ : { right: 4, width: ZOOM_SLIDER_SIZE, orient: "vertical" };
+ return [
+ { type: "inside", ...axisIndex },
+ { type: "slider", ...axisIndex, ...slider },
+ ];
+}
+
+/**
+ * With `defaults="v3"`, where a reference line's label sits. Every label used
+ * to sit above its line, so lines close together printed their labels on top
+ * of each other. The highest line keeps its label above it, the lowest goes
+ * below, and the lines between alternate the two.
+ */
+function referenceLabelPosition(
+ lines: ChartReferenceLine[],
+ line: ChartReferenceLine,
+): "insideEndTop" | "insideEndBottom" {
+ if (lines.length < 2) return "insideEndTop";
+ const rank = [...lines].sort((a, b) => b.value - a.value).indexOf(line);
+ return rank === lines.length - 1 || rank % 2 === 1
+ ? "insideEndBottom"
+ : "insideEndTop";
+}
+
+/**
+ * Reference lines as an ECharts `markLine` on the first series, at values of
+ * the value axis (`yAxis`, or `xAxis` on horizontal bars).
+ */
+function referenceMarkLine(
+ ctx: OptionBuilderContext,
+ valueAxis: "xAxis" | "yAxis",
+): Record | undefined {
+ const lines = ctx.referenceLines?.filter((l) => Number.isFinite(l.value));
+ if (!lines?.length) return undefined;
+ const ui = ctx.ui ?? FALLBACK_UI_TOKENS;
+ const field = ctx.yFields[0] ?? "";
+ // The axis format, so an unlabelled line reads like the ticks ("30M"), not
+ // like the full-value tooltip ("30,000,000").
+ const format = ctx.axisValueFormatter ?? ctx.valueFormatter;
+ return {
+ silent: true,
+ symbol: "none",
+ lineStyle: { color: ui.axisTitle, type: "dashed", width: 1 },
+ label: { color: ui.axisTitle, position: "insideEndTop" },
+ data: lines.map((line) => ({
+ [valueAxis]: line.value,
+ label: {
+ ...(ctx.v3 ? { position: referenceLabelPosition(lines, line) } : {}),
+ formatter:
+ line.label ??
+ (format ? format(line.value, field) : String(line.value)),
+ },
+ })),
+ };
+}
+
+/** Share of the value range left between a reference line and the plot edge. */
+const REFERENCE_LINE_HEADROOM = 0.08;
+
+/** The largest "nice" number (see NICE_STEPS) <= `value`, for a positive value. */
+function niceFloor(value: number): number {
+ if (!(value > 0)) return 0;
+ const magnitude = 10 ** Math.floor(Math.log10(value));
+ const step = [...NICE_STEPS]
+ .reverse()
+ .find((m) => m * magnitude <= value * (1 + 1e-9));
+ return (step ?? 1) * magnitude;
+}
+
+/** A value-axis max rounded up to a nice number, so the axis ends on a round tick. */
+function niceMax(value: number): number {
+ return value > 0 ? niceCeil(value) : value < 0 ? -niceFloor(-value) : 0;
+}
+
+/** A value-axis min rounded down to a nice number, so a line near the edge stays inside. */
+function niceMin(value: number): number {
+ return value > 0 ? niceFloor(value) : value < 0 ? -niceCeil(-value) : 0;
+}
+
+/**
+ * Value-axis `min`/`max` that keep every reference line inside the plot. A
+ * function returning `undefined` leaves the bound to ECharts, so the axis only
+ * changes when a line lies outside what the data (and zero, unless the axis
+ * fits the data) would span.
+ */
+function referenceAxisRange(
+ ctx: OptionBuilderContext,
+ includeZero: boolean,
+): Record {
+ const values = (ctx.referenceLines ?? [])
+ .map((l) => l.value)
+ .filter(Number.isFinite);
+ if (!values.length) return {};
+ const hi = Math.max(...values);
+ const lo = Math.min(...values);
+ const bounds = ({ min, max }: { min: number; max: number }) => ({
+ lower: includeZero ? Math.min(min, 0) : min,
+ upper: includeZero ? Math.max(max, 0) : max,
+ });
+ const pad = (a: number, b: number) =>
+ Math.abs(b - a) * REFERENCE_LINE_HEADROOM || 1;
+ return {
+ max: (extent: { min: number; max: number }) => {
+ const { lower, upper } = bounds(extent);
+ return hi > upper ? niceMax(hi + pad(lower, hi)) : undefined;
+ },
+ min: (extent: { min: number; max: number }) => {
+ const { lower, upper } = bounds(extent);
+ return lo < lower ? niceMin(lo - pad(lo, upper)) : undefined;
+ },
+ };
+}
+
+/** Corner radius of a bar's rounded end, in px. */
+const BAR_RADIUS = 4;
+
+/** The numeric value of a bar data item (a number or `{ value }`), or null. */
+function barItemValue(item: unknown): number | null {
+ const raw =
+ item !== null && typeof item === "object" && "value" in item
+ ? (item as { value: unknown }).value
+ : item;
+ return toFiniteNumber(raw);
+}
+
+/**
+ * Rounds only the free end of each bar. Corner radius used to be set per
+ * series, which rounded every segment of a stack (notches at each joint) and
+ * rounded negative bars at the zero line, with a square far end. Now:
+ *
+ * - unstacked bars keep the series radius at the end away from zero; a
+ * negative value gets its own radius at its far end;
+ * - in a stack, only the outermost segment of the positive side and of the
+ * negative side is rounded; the series radius is 0. Zero and missing
+ * values are never outermost, so a gap in the middle does not matter.
+ *
+ * Per-item radii are plain `itemStyle` on the data item, so selection
+ * emphasis keeps them, and {@link mergeChartOptions} drops them when the
+ * caller sets a series radius.
+ */
+function roundBarEnds(
+ series: Record[],
+ horizontal: boolean,
+): Record[] {
+ const r = BAR_RADIUS;
+ const positive = horizontal ? [0, r, r, 0] : [r, r, 0, 0];
+ const negative = horizontal ? [r, 0, 0, r] : [0, 0, r, r];
+ const square = [0, 0, 0, 0];
+ // The last series with a positive (and with a negative) value, per stack and
+ // category.
+ const outermost = new Map();
+ for (const s of series) {
+ if (s.type !== "bar" || !s.stack || !Array.isArray(s.data)) continue;
+ s.data.forEach((item, i) => {
+ const n = barItemValue(item);
+ if (n) outermost.set(`${s.stack}|${i}|${n > 0 ? "+" : "-"}`, s);
+ });
+ }
+ return series.map((s) => {
+ if (s.type !== "bar" || !Array.isArray(s.data)) return s;
+ const stacked = Boolean(s.stack);
+ const data = s.data.map((item, i) => {
+ const n = barItemValue(item);
+ if (!n) return item;
+ const isOuter =
+ outermost.get(`${s.stack}|${i}|${n > 0 ? "+" : "-"}`) === s;
+ const radius = stacked
+ ? isOuter
+ ? n > 0
+ ? positive
+ : negative
+ : undefined
+ : n < 0
+ ? negative
+ : undefined;
+ if (!radius) return item;
+ const own: Record =
+ item !== null && typeof item === "object"
+ ? (item as Record)
+ : { value: item };
+ return {
+ ...own,
+ itemStyle: {
+ ...(own.itemStyle as Record | undefined),
+ borderRadius: radius,
+ },
+ };
+ });
+ return {
+ ...s,
+ data,
+ itemStyle: {
+ ...(s.itemStyle as Record | undefined),
+ borderRadius: stacked ? square : positive,
+ },
+ };
+ });
+}
+
+/** Adds the reference lines to the first series of `series`. */
+function withReferenceLines(
+ series: Record[],
+ ctx: OptionBuilderContext,
+ valueAxis: "xAxis" | "yAxis",
+): Record[] {
+ const markLine = referenceMarkLine(ctx, valueAxis);
+ if (!markLine || series.length === 0) return series;
+ return [{ ...series[0], markLine }, ...series.slice(1)];
+}
+
+/**
+ * Axis name settings. Today: the field name at the end of the axis. With
+ * `defaults="v3"` the card title carries the axis meaning, so names are left
+ * off, except on scatter charts (two measures), where they are centred below
+ * and beside the axis.
+ */
+function axisName(
+ ctx: OptionBuilderContext,
+ isScatter: boolean,
+ axis: "x" | "y",
+ field: string | undefined,
+): Record {
+ if (!field) return {};
+ if (!ctx.v3) return { name: formatLabel(field) };
+ if (!isScatter) return {};
+ return {
+ name: formatLabel(field),
+ nameLocation: "middle",
+ nameGap: axis === "x" ? 28 : scatterYNameGap(ctx, field),
+ // A long name is cut to the plot height, not run past it.
+ ...(axis === "y" && ctx.chartHeight
+ ? {
+ nameTruncate: {
+ maxWidth: Math.max(60, Math.round(ctx.chartHeight * 0.6)),
+ ellipsis: "...",
+ },
+ }
+ : {}),
+ };
+}
+
+/** Width of a tick label of a value axis, in px (chars times 7, plus margin). */
+const TICK_CHAR_WIDTH = 7;
+/** Left margin of a scatter plot that carries a y axis name, in px. */
+const SCATTER_Y_NAME_MARGIN = 28;
+
+/**
+ * Gap between the y axis and its name: the widest tick label plus a margin,
+ * so the name clears the ticks ("Churn" used to land on "40").
+ */
+function scatterYNameGap(ctx: OptionBuilderContext, field: string): number {
+ const format = ctx.axisValueFormatter ?? ctx.valueFormatter;
+ const values = (ctx.yDataMap[field] ?? [])
+ .map((v) => toFiniteNumber(v))
+ .filter((v): v is number => v !== null);
+ const widest = Math.max(
+ 1,
+ ...values.map((v) =>
+ format
+ ? format(v, field).length
+ : String(Math.round(v * 100) / 100).length,
+ ),
+ );
+ return widest * TICK_CHAR_WIDTH + 16;
+}
+
export function buildCartesianOption(
ctx: CartesianContext,
): Record {
@@ -412,73 +1699,447 @@ export function buildCartesianOption(
symbolSize,
interactive,
} = ctx;
+ const isValueX = ctx.isValueX === true;
const hasMultipleSeries = ctx.yFields.length > 1;
- const seriesType = chartType === "area" ? "line" : chartType;
const isScatter = chartType === "scatter";
- const isLineLike = chartType === "line" || chartType === "area";
+ // A single-measure scatter names its y axis.
+ const yNamed = ctx.yFields.length === 1;
+ // Fields drawn against a second value axis on the right.
+ const rightFields = isScatter
+ ? []
+ : ctx.yFields.filter((f) => ctx.seriesConfig?.[f]?.axis === "right");
+ const leftFields = ctx.yFields.filter((f) => !rightFields.includes(f));
+ // A scatter over dates plots them on a time axis, not as epoch numbers.
+ const isTimeScatter = isScatter && isTimeSeries;
+ // Bars over dates use a category axis of formatted dates: on a time axis
+ // the first and last bars stick out of the plot, the first tick labels
+ // collide ("2026" over "2") and the last label is dropped.
+ const isTimeBar = chartType === "bar" && isTimeSeries;
+ const isTimeAxis = isTimeSeries && !isTimeBar && !isScatter;
+ // Zoom runs along the category or time axis; scatter has none.
+ const zoom = ctx.zoom === true && !isScatter;
+ const dateLabel = (value: string | number) =>
+ formatTimeLabel(Number(value), ctx.xDateOnly === true);
+ const leftAxis = {
+ type: "value",
+ // Scatter axes fit the data instead of starting at 0.
+ ...(isScatter ? { scale: true } : {}),
+ ...axisName(
+ ctx,
+ isScatter,
+ "y",
+ ctx.yFields.length === 1 ? ctx.yFields[0] : undefined,
+ ),
+ ...mergeAxisLabel(ui, valueAxisLabel(ctx, leftFields[0])),
+ ...referenceAxisRange(ctx, !isScatter),
+ };
return {
...buildBaseOption(ctx),
- tooltip: { ...tooltipTokens(ui), trigger: isScatter ? "item" : "axis" },
+ tooltip: {
+ ...tooltipTokens(ui),
+ trigger: isScatter ? "item" : "axis",
+ // Scatter: both measures, named, not just y.
+ ...(isScatter ? { formatter: scatterTooltip(ctx, isTimeScatter) } : {}),
+ // Stacked bars and areas: every series and the total, top band first.
+ ...(stacked &&
+ hasMultipleSeries &&
+ (chartType === "bar" || chartType === "area")
+ ? {
+ formatter: stackedTooltip(
+ ctx,
+ true,
+ new Set(
+ ctx.yFields.filter((f) => {
+ const own = ctx.seriesConfig?.[f]?.type ?? chartType;
+ return own === "bar" || own === "area";
+ }),
+ ),
+ ),
+ }
+ : {}),
+ },
legend:
ctx.showLegend && hasMultipleSeries
- ? { top: "bottom", ...legendTextStyle(ui) }
+ ? zoom
+ ? { bottom: ZOOM_SLIDER_SIZE + 12, ...seriesLegend(ui, ctx) }
+ : { top: "bottom", ...seriesLegend(ui, ctx) }
: undefined,
+ ...(zoom ? { dataZoom: zoomComponents("x") } : {}),
grid: {
- left: "10%",
+ left: ctx.v3 && isScatter && yNamed ? SCATTER_Y_NAME_MARGIN : "10%",
right: "10%",
- top: ctx.title ? "15%" : "10%",
- bottom: ctx.showLegend && hasMultipleSeries ? "20%" : "15%",
+ // A title needs a fixed number of pixels, not a share of the height
+ // (15% of 220 px left it on the top tick).
+ top: ctx.title
+ ? ctx.chartHeight
+ ? Math.max(TITLE_BAND, Math.round(ctx.chartHeight * 0.15))
+ : "15%"
+ : "10%",
+ // With zoom, room for the slider (and the legend above it).
+ bottom: zoom
+ ? ctx.showLegend && hasMultipleSeries
+ ? ZOOM_SLIDER_SIZE + 52
+ : ZOOM_SLIDER_SIZE + 20
+ : ctx.v3 && isScatter && ctx.xField
+ ? // The x axis name sits between the ticks and the legend row.
+ (ctx.showLegend && hasMultipleSeries ? LEGEND_BAND : 0) +
+ SCATTER_X_NAME_BAND
+ : ctx.showLegend && hasMultipleSeries
+ ? LEGEND_BAND
+ : "15%",
containLabel: true,
},
xAxis: {
- type: isScatter ? "value" : isTimeSeries ? "time" : "category",
- data: isScatter || isTimeSeries ? undefined : ctx.xData,
- name: ctx.xField ? formatLabel(ctx.xField) : undefined,
+ type: isTimeScatter
+ ? "time"
+ : isScatter || isValueX
+ ? "value"
+ : isTimeAxis
+ ? "time"
+ : "category",
+ ...(isScatter && !isTimeScatter ? { scale: true } : {}),
+ data: isScatter || isValueX || isTimeAxis ? undefined : ctx.xData,
+ // Date-only data: the tooltip header shows the day, not midnight.
+ // (Omit the key otherwise: an explicit `undefined` breaks ECharts.)
+ // DATE values: no ticks between days. A single date gets a day of
+ // padding each side (an hour for timestamps) instead of spanning two
+ // days of hourly ticks.
+ ...(isTimeAxis && ctx.xDateOnly ? { minInterval: DAY_MS } : {}),
+ ...(isTimeAxis && ctx.xData.length === 1
+ ? singleDateRange(Number(ctx.xData[0]), ctx.xDateOnly === true)
+ : {}),
+ ...(isTimeAxis && ctx.xDateOnly
+ ? {
+ axisPointer: {
+ label: {
+ formatter: (params: { value: number }) =>
+ formatLocalDate(params.value),
+ },
+ },
+ }
+ : {}),
+ ...(isTimeBar
+ ? {
+ axisPointer: {
+ label: {
+ formatter: (params: { value: string | number }) =>
+ dateLabel(params.value),
+ },
+ },
+ }
+ : {}),
+ ...axisName(ctx, isScatter, "x", ctx.xField),
...mergeAxisLabel(
ui,
- isScatter || isTimeSeries
- ? { show: true }
- : {
- rotate: ctx.xData.length > 10 ? 45 : 0,
- formatter: (v: string) => truncateLabel(String(v), 10),
- },
+ isTimeAxis || isTimeScatter
+ ? // Bold month or year labels printed over the day labels next to
+ // them; ECharts drops the label that would overlap.
+ { show: true, hideOverlap: true }
+ : isScatter || isValueX
+ ? {
+ show: true,
+ hideOverlap: true,
+ ...(isScatter && !isTimeScatter ? scatterXTickFormat() : {}),
+ }
+ : isTimeBar
+ ? {
+ ...dateBarXAxisLabel(ctx, ctx.xData.length),
+ formatter: dateLabel,
+ }
+ : categoryXAxisLabel(ctx, ctx.xData.length, 10),
),
},
- yAxis: {
- type: "value",
- name: ctx.yFields.length === 1 ? formatLabel(ctx.yFields[0]) : undefined,
- ...mergeAxisLabel(ui, valueAxisLabel(ctx)),
- },
- series: ctx.yFields.map((key, idx) => ({
- name: formatLabel(key),
- type: seriesType,
- data: isScatter
- ? ctx.xData.map((x, i) => [x, ctx.yDataMap[key][i]])
- : isTimeSeries
- ? createTimeSeriesData(ctx.xData, ctx.yDataMap[key])
- : ctx.yDataMap[key],
- smooth: isLineLike ? smooth : undefined,
- showSymbol: isLineLike ? showSymbol : undefined,
- symbol: isScatter ? "circle" : undefined,
- // Symbol size applies to line/area as well as scatter, so an interactive
- // line can present a clickable point, not just a hairline.
- symbolSize: isScatter || isLineLike ? symbolSize : undefined,
- // Fire click events along the whole line stroke, not only on symbols,
- // when the chart is interactive. No effect on non-line series.
- triggerLineEvent: isLineLike && interactive ? true : undefined,
- areaStyle: chartType === "area" ? { opacity: 0.3 } : undefined,
- stack: stacked && chartType === "area" ? "total" : undefined,
- itemStyle:
- chartType === "bar" ? { borderRadius: [4, 4, 0, 0] } : undefined,
- color: ctx.colors[idx % ctx.colors.length],
- tooltip: ctx.valueFormatter
- ? {
- valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key),
- }
- : undefined,
- })),
+ yAxis: rightFields.length
+ ? [
+ leftAxis,
+ {
+ type: "value",
+ position: "right",
+ // One set of grid lines: the left axis draws them.
+ ...mergeAxisLabel(ui, valueAxisLabel(ctx, rightFields[0])),
+ splitLine: { show: false },
+ },
+ ]
+ : leftAxis,
+ series: withReferenceLines(
+ roundBarEnds(cartesianSeries(), false),
+ ctx,
+ "yAxis",
+ ),
};
+
+ /**
+ * Ticks of a scatter x axis, compact like the y axis ("2M", not
+ * "2,000,000"). Only once the values reach 10,000, so years and small
+ * numbers keep their digits.
+ */
+ function scatterXTickFormat(): Record {
+ const largest = Math.max(
+ 0,
+ ...ctx.xData.map((x) => Math.abs(toFiniteNumber(x) ?? 0)),
+ );
+ return largest >= SCATTER_COMPACT_X_MIN && ctx.axisValueFormatter
+ ? valueAxisLabel(ctx, ctx.xField)
+ : {};
+ }
+
+ function cartesianSeries(): Record[] {
+ return ctx.yFields.map((key, idx) => {
+ const config = isScatter ? undefined : ctx.seriesConfig?.[key];
+ // A series may be drawn as another type than the chart (combo charts).
+ const own = config?.type ?? chartType;
+ const ownLineLike = own === "line" || own === "area";
+ return {
+ name: formatLabel(key),
+ type: own === "area" ? "line" : own,
+ ...(config?.axis === "right" ? { yAxisIndex: 1 } : {}),
+ data: isScatter
+ ? scatterPoints(ctx.xData, ctx.yDataMap[key])
+ : isValueX
+ ? ctx.xData.map((x, i) => [x, ctx.yDataMap[key][i]])
+ : isTimeAxis
+ ? createTimeSeriesData(ctx.xData, ctx.yDataMap[key])
+ : own === "bar" && !stacked
+ ? withSignedLabels(ctx, ctx.yDataMap[key], "bottom")
+ : ctx.yDataMap[key],
+ smooth: ownLineLike ? smooth : undefined,
+ connectNulls: ownLineLike && ctx.connectNulls ? true : undefined,
+ // A series with one point has no line to draw: show its symbol.
+ showSymbol: ownLineLike
+ ? showSymbol || countValues(ctx.yDataMap[key]) <= 1
+ : undefined,
+ // A single bar would fill most of the plot.
+ ...(own === "bar" && ctx.xData.length === 1
+ ? { barMaxWidth: SINGLE_BAR_MAX_WIDTH }
+ : {}),
+ symbol: isScatter ? "circle" : undefined,
+
+ // Symbol size applies to line/area as well as scatter, so an interactive
+ // line can present a clickable point, not just a hairline.
+ // A scatter point under 2 px is invisible (0 drew nothing).
+ symbolSize: isScatter
+ ? Math.max(MIN_SCATTER_SYMBOL, symbolSize)
+ : ownLineLike
+ ? symbolSize
+ : undefined,
+ // Fire click events along the whole line stroke, not only on symbols,
+ // when the chart is interactive. No effect on non-line series.
+ triggerLineEvent: ownLineLike && interactive ? true : undefined,
+ // Unstacked overlapping fills blend into a third color; keep them
+ // faint so the lines carry the series.
+ areaStyle:
+ own === "area"
+ ? { opacity: stacked || !hasMultipleSeries ? 0.3 : 0.12 }
+ : undefined,
+ label:
+ own === "bar" || isScatter
+ ? valueLabel(ctx, key, own === "bar" && stacked ? "inside" : "top")
+ : undefined,
+ ...valueLabelLayout(ctx, own === "bar" || isScatter),
+ // Series stack with others of the same type on the same axis.
+ stack:
+ stacked && (own === "area" || own === "bar")
+ ? ctx.seriesConfig
+ ? `${own}-${config?.axis ?? "left"}`
+ : "total"
+ : undefined,
+ itemStyle:
+ own === "bar"
+ ? { borderRadius: [4, 4, 0, 0] }
+ : isScatter
+ ? // Overlapping points stay visible: opacity falls with the count.
+ { opacity: scatterOpacity(ctx.xData.length) }
+ : undefined,
+ color: ctx.colors[idx % ctx.colors.length],
+ tooltip: ctx.valueFormatter
+ ? {
+ valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key),
+ }
+ : undefined,
+ };
+ });
+ }
+}
+
+// ============================================================================
+// Custom Options Merge
+// ============================================================================
+
+/** Custom ECharts options: an object to deep-merge, or a function of the built option. */
+export type ChartOptionsInput =
+ | Record
+ | ((built: Record) => Record);
+
+/** Option keys whose arrays hold one component per entry, merged by index. */
+const INDEXED_KEYS = new Set([
+ "series",
+ "xAxis",
+ "yAxis",
+ "grid",
+ "dataZoom",
+ "visualMap",
+]);
+
+function isPlainObject(value: unknown): value is Record {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+function deepMerge(
+ base: Record,
+ patch: Record,
+): Record