From 5cf1b4b1fec029e9cdff07f63d2830a202fddefa Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:40:55 +0000 Subject: [PATCH 001/151] feat(appkit-ui): add defaults="v3" chart prop for behaviour-changing defaults Adds the ChartDefaults type and a `defaults` prop on every chart. Later commits gate defaults that change how a correct chart looks behind `defaults="v3"`; bug fixes apply without it. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- packages/appkit-ui/src/react/charts/base.tsx | 3 +++ packages/appkit-ui/src/react/charts/index.ts | 1 + packages/appkit-ui/src/react/charts/types.ts | 14 ++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 28b1ca831..f5435f406 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -45,6 +45,7 @@ import type { ChartClickDatum, ChartColorPalette, ChartData, + ChartDefaults, ChartType, ChartValueFormatter, Orientation, @@ -189,6 +190,8 @@ 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; } // ============================================================================ diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts index 0cd6723b4..f7c4895a0 100644 --- a/packages/appkit-ui/src/react/charts/index.ts +++ b/packages/appkit-ui/src/react/charts/index.ts @@ -109,6 +109,7 @@ export type { ChartColorPalette, ChartData, ChartDataInput, + ChartDefaults, ChartRow, ChartType, ChartUITokens, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index f84fb1735..e58f73265 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -54,6 +54,14 @@ export type ChartValueFormatter = ( // Base Props (shared by all charts) // ============================================================================ +/** + * Default set a chart renders with. `"v3"` opts into the defaults that change + * how existing charts look (null kept as a gap, 300 px height, bar orientation + * from the data, first row on top, straight lines, compact number formats, ...). + * Leave unset to keep the current behaviour. + */ +export type ChartDefaults = "v3"; + /** Color palette types for different visualization needs */ export type ChartColorPalette = "categorical" | "sequential" | "diverging"; @@ -99,6 +107,12 @@ export interface ChartBaseProps { /** Y-axis field key(s). Auto-detected from schema if not provided. */ yKey?: string | string[]; + /** + * Opt into the v3 defaults. See {@link ChartDefaults}. Bug fixes apply with or + * without it; only defaults that change the look of a correct chart are gated. + */ + defaults?: ChartDefaults; + /** Accessibility label for screen readers */ ariaLabel?: string; /** Test ID for automated testing */ From 52dd0d994c0b1095511999bf709d953b1d277bd4 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:44:39 +0000 Subject: [PATCH 002/151] feat(appkit-ui): decide the x axis type from the xKey values, add xType Time-axis mode was decided from every column and from column names, so a measure named avg_response_time, an unused previous_period column or any extra DATE column put a category chart on a time axis and drew nothing. Date fields are now detected from their values only, and the axis type comes from the resolved xKey column (Arrow temporal types count as time). A new xType prop (time, category or value) overrides the inference; value plots x on a numeric axis. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 59 +++++++++++++ .../react/charts/__tests__/options.test.ts | 28 +++++++ packages/appkit-ui/src/react/charts/base.tsx | 19 ++++- packages/appkit-ui/src/react/charts/index.ts | 2 + .../appkit-ui/src/react/charts/normalize.ts | 82 +++++++++++++++---- .../appkit-ui/src/react/charts/options.ts | 21 +++-- packages/appkit-ui/src/react/charts/types.ts | 13 +++ 7 files changed, 197 insertions(+), 27 deletions(-) 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..6bb58539f 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -506,3 +506,62 @@ describe("normalizeHeatmapData", () => { expect(result.max).toBe(42); }); }); + +describe("x axis type from the xKey values (C1)", () => { + 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"]); + }); +}); 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..f8542a1f0 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -1353,3 +1353,31 @@ describe("applySelectionEmphasis", () => { }); }); }); + +describe("xType value axis (C1)", () => { + 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], + ]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index f5435f406..dce5bda8d 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -49,6 +49,7 @@ import type { ChartType, ChartValueFormatter, Orientation, + XAxisType, } from "./types"; import { mapToDatum } from "./utils"; @@ -123,6 +124,8 @@ export interface BaseChartProps { xKey?: string; /** Y-axis field key(s) (auto-detected from schema if not provided) */ yKey?: string | string[]; + /** X axis type override. Inferred from the `xKey` values when unset. */ + xType?: XAxisType; /** Chart orientation @default "vertical" */ orientation?: Orientation; /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */ @@ -207,6 +210,7 @@ export function BaseChart({ chartType, xKey, yKey, + xType, orientation, height, title, @@ -280,13 +284,20 @@ export function BaseChart({ () => chartType === "heatmap" ? normalizeHeatmapData(data, xKey, yAxisKey, yKey) - : normalizeChartData(data, xKey, yKey, orientation), - [data, xKey, yKey, yAxisKey, orientation, chartType], + : normalizeChartData(data, xKey, yKey, orientation, { xType }), + [data, xKey, yKey, yAxisKey, orientation, chartType, xType], ); // Memoize option building const option = useMemo(() => { - const { xData, yFields, xField, chartType: detectedChartType } = normalized; + const { + xData, + yFields, + xField, + chartType: detectedChartType, + xAxisType, + } = normalized; + const isValueX = xAxisType === "value"; if (xData.length === 0) return null; @@ -316,6 +327,7 @@ export function BaseChart({ !isHeatmap && (orientation === "horizontal" || (detectedChartType === "categorical" && + !isValueX && !orientation && chartType === "bar")); const isTimeSeries = @@ -359,6 +371,7 @@ export function BaseChart({ ...baseCtx, chartType, isTimeSeries, + isValueX: isValueX && !isHorizontal, stacked, smooth, showSymbol, diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts index f7c4895a0..6b4bcd5e4 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"; @@ -133,6 +134,7 @@ export type { ScatterChartProps, ScatterChartSpecificProps, UnifiedChartProps, + XAxisType, } from "./types"; // Type guards diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 93c624c18..c6e9da360 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -1,13 +1,15 @@ import type { Table } from "apache-arrow"; import { ArrowClient } from "@/js"; +import { getTypeIdSets } from "@/js/arrow/lazy-arrow"; -import { DATE_FIELD_PATTERNS, NAME_FIELD_PATTERNS } from "./constants"; +import { NAME_FIELD_PATTERNS } from "./constants"; import type { ChartData, NormalizedChartData, NormalizedChartDataBase, Orientation, + XAxisType, } from "./types"; import { isArrowTable } from "./types"; import { @@ -56,6 +58,28 @@ 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 present = 0; + for (const value of values) { + if (isMissing(value)) continue; + present++; + if (!isDateString(value)) return "category"; + } + return present > 0 ? "time" : "category"; +} + +function columnValues(data: Record[], key: string): unknown[] { + return data.map((row) => row[key]); +} + // ============================================================================ // Field Detection // ============================================================================ @@ -78,15 +102,11 @@ function detectFieldsFromJson( 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 valueIsDateString = isDateString(value); - return keyMatchesDatePattern || valueIsDateString; - }); + // Date fields are decided by their values, never by their names: a measure + // named `avg_response_time` is not a date. + const dateFields = keys.filter( + (key) => inferXType(columnValues(data, key)) === "time", + ); // Detect name/category fields by pattern AND value type let nameFields = keys.filter((key) => { @@ -189,6 +209,7 @@ function extractFromJson( data: Record[], xField: string, yFields: string[], + xIsDateField: boolean, ): { xData: (string | number)[]; yDataMap: Record; @@ -200,8 +221,6 @@ function extractFromJson( 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) { @@ -220,11 +239,28 @@ function extractFromJson( * Normalizes chart data from either Arrow or JSON format. * Converts BigInt and Date values to chart-compatible types. */ +/** Extra normalization options. */ +export interface NormalizeOptions { + /** Overrides the x axis type inferred from the `xKey` values. */ + xType?: XAxisType; +} + +function isArrowTemporalField(table: Table, key: string): boolean { + const field = table.schema.fields.find((f) => f.name === key); + if (!field) return false; + try { + return getTypeIdSets().temporal.has(field.typeId); + } catch { + return false; + } +} + export function normalizeChartData( data: ChartData, xKey?: string, yKey?: string | string[], orientation?: Orientation, + opts: NormalizeOptions = {}, ): NormalizedChartData { if (isArrowTable(data)) { const table = data as Table; @@ -239,13 +275,20 @@ export function normalizeChartData( const { xData: rawXData, yDataMap: rawYDataMap } = ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys); + const xAxisType: XAxisType = + opts.xType ?? + (isArrowTemporalField(table, resolvedXKey) + ? "time" + : inferXType(rawXData)); + const chartType = xAxisType === "time" ? "timeseries" : "categorical"; + let xData = toChartArray(rawXData); let yDataMap: Record = {}; for (const key of resolvedYKeys) { yDataMap[key] = toChartArray(rawYDataMap[key] ?? []); } - if (detected.chartType === "timeseries") { + if (chartType === "timeseries") { ({ xData, yDataMap } = sortTimeSeriesAscending( xData, yDataMap, @@ -264,7 +307,8 @@ export function normalizeChartData( yDataMap, xField: resolvedXKey, yFields: resolvedYKeys, - chartType: detected.chartType, + chartType, + xAxisType, }; } @@ -278,10 +322,15 @@ export function normalizeChartData( : [yKey] : detected.yFields; + 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", ); let xData = toChartArray(rawXData); @@ -290,7 +339,7 @@ export function normalizeChartData( yDataMap[key] = toChartArray(rawYDataMap[key] ?? []); } - if (detected.chartType === "timeseries") { + if (chartType === "timeseries") { ({ xData, yDataMap } = sortTimeSeriesAscending( xData, yDataMap, @@ -309,7 +358,8 @@ export function normalizeChartData( yDataMap, xField: resolvedXKey, yFields: resolvedYKeys, - chartType: detected.chartType, + chartType, + xAxisType, }; } diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 84b64e404..92666d630 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -26,6 +26,8 @@ export interface OptionBuilderContext { export interface CartesianContext extends OptionBuilderContext { chartType: ChartType; isTimeSeries: boolean; + /** Plot x on a numeric value axis (`xType="value"`). */ + isValueX?: boolean; stacked: boolean; smooth: boolean; showSymbol: boolean; @@ -412,6 +414,7 @@ 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"; @@ -432,12 +435,13 @@ export function buildCartesianOption( containLabel: true, }, xAxis: { - type: isScatter ? "value" : isTimeSeries ? "time" : "category", - data: isScatter || isTimeSeries ? undefined : ctx.xData, + type: + isScatter || isValueX ? "value" : isTimeSeries ? "time" : "category", + data: isScatter || isValueX || isTimeSeries ? undefined : ctx.xData, name: ctx.xField ? formatLabel(ctx.xField) : undefined, ...mergeAxisLabel( ui, - isScatter || isTimeSeries + isScatter || isValueX || isTimeSeries ? { show: true } : { rotate: ctx.xData.length > 10 ? 45 : 0, @@ -453,11 +457,12 @@ export function buildCartesianOption( 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], + data: + isScatter || isValueX + ? 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, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index e58f73265..1cec8f852 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -24,6 +24,12 @@ export type DataFormat = /** Chart orientation */ export type Orientation = "vertical" | "horizontal"; +/** + * X axis type. `"time"` for dates, `"category"` for labels, `"value"` for a + * numeric axis. Charts infer it from the `xKey` values; pass `xType` to override. + */ +export type XAxisType = "time" | "category" | "value"; + /** Supported chart types */ export type ChartType = | "bar" @@ -106,6 +112,11 @@ export interface ChartBaseProps { xKey?: string; /** Y-axis field key(s). Auto-detected from schema if not provided. */ yKey?: string | string[]; + /** + * X axis type (cartesian charts). Inferred from the `xKey` values only, never + * from column names: all dates gives `"time"`, otherwise `"category"`. + */ + xType?: XAxisType; /** * Opt into the v3 defaults. See {@link ChartDefaults}. Bug fixes apply with or @@ -326,6 +337,8 @@ export interface NormalizedChartDataBase { xField: string; yFields: string[]; chartType: "timeseries" | "categorical"; + /** Resolved x axis type, from `xType` or the `xKey` values. */ + xAxisType?: XAxisType; } /** Normalized chart data for rendering (standard charts) */ From 73fc6f768bcc66569c0167882f711d0dab82cbda Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:45:09 +0000 Subject: [PATCH 003/151] test(appkit-ui): axis type no longer depends on column names or the first row Fixed by C1: the axis type comes from all xKey values. YYYY-MM strings are categories under month and period alike, epoch numbers get the same axis under ts and timestamp, and a null in the first row no longer turns a date column into categories. Epoch numbers stay categories (pass xType="time" to plot them as dates). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) 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 6bb58539f..84d89cc48 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -565,3 +565,36 @@ describe("x axis type from the xKey values (C1)", () => { expect(result.xData).toEqual(["2026-01-01", "2026-01-02"]); }); }); + +describe("axis type ignores column names and the first row (X6)", () => { + 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"); + }); +}); From f75abd8b0c95dff4b7a8cf98c8204230fd1933c0 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:45:16 +0000 Subject: [PATCH 004/151] test(appkit-ui): uptime_pct is not auto-detected as a date column Fixed by C1: date columns are detected from values, not names, so rows of customer, monthly_spend and uptime_pct put customer on x instead of uptime_pct. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/normalize.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 84d89cc48..18181b054 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -598,3 +598,16 @@ describe("axis type ignores column names and the first row (X6)", () => { expect(normalizeChartData(data, "day", "n").chartType).toBe("timeseries"); }); }); + +describe("scatter auto-detection (SCAT-01)", () => { + 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"]); + }); +}); From 13f63f4e198cbe7ff9a197c1cc33dbf2005cbc3c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:45:55 +0000 Subject: [PATCH 005/151] fix(appkit-ui): keep a given key out of the other axis's auto-detection With only one of xKey and yKey given, the other was auto-detected and could be the same column, which drew a y = x diagonal. A key the caller gave is now excluded when the other axis is detected, in both the JSON and Arrow paths. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 19 +++++++ .../appkit-ui/src/react/charts/normalize.ts | 52 ++++++++++++++----- 2 files changed, 59 insertions(+), 12 deletions(-) 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 18181b054..a1e4dd7a8 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -611,3 +611,22 @@ describe("scatter auto-detection (SCAT-01)", () => { expect(result.yFields).toEqual(["monthly_spend", "uptime_pct"]); }); }); + +describe("one key given (SCAT-03)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index c6e9da360..717a43320 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -239,6 +239,34 @@ 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, + }; +} + /** Extra normalization options. */ export interface NormalizeOptions { /** Overrides the x axis type inferred from the `xKey` values. */ @@ -265,12 +293,12 @@ export function normalizeChartData( 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 { resolvedXKey, resolvedYKeys } = resolveKeys( + detected, + table.schema.fields.map((f) => f.name), + xKey, + yKey, + ); const { xData: rawXData, yDataMap: rawYDataMap } = ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys); @@ -315,12 +343,12 @@ export function normalizeChartData( // 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)); From 80855914bcd0896e807cbfa7c8e8f531c0ea20e2 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:47:17 +0000 Subject: [PATCH 006/151] fix(appkit-ui): show an error state for an xKey, yKey or yAxisKey not in the rows A key that was not in the data drew a flat zero series with no error or warning. BaseChart now checks the given keys against the Arrow schema or the row keys, renders an error state in the chart box that names the unknown keys and lists the available ones, and logs it with console.error. The check is a generic helper (unknownKeysMessage) so other charts can reuse it. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 29 ++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 29 ++++++++++++++-- .../appkit-ui/src/react/charts/normalize.ts | 33 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) 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..58eb498ea 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -331,3 +331,32 @@ describe("BaseChart sizing", () => { expect(root.style.minHeight).toBe(""); }); }); + +describe("unknown keys (C3)", () => { + 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"'); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index dce5bda8d..3cc3cff60 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -26,10 +26,14 @@ 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 } from "react"; import { chartSizeStyle } from "./constants"; -import { normalizeChartData, normalizeHeatmapData } from "./normalize"; +import { + normalizeChartData, + normalizeHeatmapData, + unknownKeysMessage, +} from "./normalize"; import { applySelectionEmphasis, buildCartesianOption, @@ -279,6 +283,15 @@ export function BaseChart({ } }, []); + // A key that is not in the rows would draw a flat zero series; report it. + const keyError = useMemo( + () => unknownKeysMessage(data, { xKey, yKey, yAxisKey }), + [data, xKey, yKey, yAxisKey], + ); + useEffect(() => { + if (keyError) console.error(`[appkit-ui] ${chartType} chart: ${keyError}`); + }, [keyError, chartType]); + // Memoize data normalization const normalized = useMemo( () => @@ -448,6 +461,18 @@ export function BaseChart({ [interactive], ); + if (keyError) { + return ( +
+ {keyError} +
+ ); + } + if (!option) { return (
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. */ From 3d5108ad822326805708b0ce819a159d2d07f988 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:49:48 +0000 Subject: [PATCH 007/151] feat(appkit-ui): keep missing measures as gaps with defaults="v3", add connectNulls Null, undefined and empty-string measures were drawn as 0 in every chart type, so a line dropped to 0 on missing days and a heatmap labelled a missing cell 0. With defaults="v3" they now stay null through the JSON and Arrow paths (ArrowClient.extractChartData gains an optional keepNulls), so lines get a gap, bars get no bar and heatmaps an empty cell that no longer pulls the color scale to 0. A connectNulls prop (default false) on line and area charts draws across gaps. Without v3 the old behaviour is unchanged. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../appkit-ui/src/js/arrow/arrow-client.ts | 46 ++++++++++++++++--- .../react/charts/__tests__/normalize.test.ts | 44 ++++++++++++++++++ .../react/charts/__tests__/options.test.ts | 28 +++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 16 +++++-- .../appkit-ui/src/react/charts/normalize.ts | 38 +++++++++++---- .../appkit-ui/src/react/charts/options.ts | 12 ++++- packages/appkit-ui/src/react/charts/types.ts | 15 +++++- packages/appkit-ui/src/react/charts/utils.ts | 34 +++++++++----- 8 files changed, 199 insertions(+), 34 deletions(-) diff --git a/packages/appkit-ui/src/js/arrow/arrow-client.ts b/packages/appkit-ui/src/js/arrow/arrow-client.ts index b2a4dc90d..9c58da11a 100644 --- a/packages/appkit-ui/src/js/arrow/arrow-client.ts +++ b/packages/appkit-ui/src/js/arrow/arrow-client.ts @@ -152,7 +152,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 +198,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 }; @@ -386,17 +417,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/react/charts/__tests__/normalize.test.ts b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts index a1e4dd7a8..3117bd0b2 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -630,3 +630,47 @@ describe("one key given (SCAT-03)", () => { expect(result.xField).toBe("uptime_pct"); }); }); + +describe("missing measures (C2, v3)", () => { + 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"]); + }); +}); 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 f8542a1f0..15c5920e8 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -1381,3 +1381,31 @@ describe("xType value axis (C1)", () => { ]); }); }); + +describe("connectNulls (C2)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 3cc3cff60..7c11826a7 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -151,6 +151,8 @@ export interface BaseChartProps { showSymbol?: boolean; /** Smooth line curves (line/area charts) @default true */ 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 */ @@ -223,6 +225,7 @@ export function BaseChart({ colors: customColors, showSymbol = false, smooth = true, + connectNulls = false, stacked = false, symbolSize = 8, showArea = true, @@ -237,7 +240,9 @@ export function BaseChart({ className, onDataClick, selected, + defaults, }: BaseChartProps) { + const v3 = defaults === "v3"; // Determine the appropriate color palette based on chart type const resolvedPalette = colorPalette ?? getDefaultPalette(chartType); const themeColors = useThemeColors(resolvedPalette); @@ -296,9 +301,12 @@ export function BaseChart({ const normalized = useMemo( () => chartType === "heatmap" - ? normalizeHeatmapData(data, xKey, yAxisKey, yKey) - : normalizeChartData(data, xKey, yKey, orientation, { xType }), - [data, xKey, yKey, yAxisKey, orientation, chartType, xType], + ? normalizeHeatmapData(data, xKey, yAxisKey, yKey, { keepNulls: v3 }) + : normalizeChartData(data, xKey, yKey, orientation, { + xType, + keepNulls: v3, + }), + [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3], ); // Memoize option building @@ -387,6 +395,7 @@ export function BaseChart({ isValueX: isValueX && !isHorizontal, stacked, smooth, + connectNulls, showSymbol, symbolSize, interactive, @@ -409,6 +418,7 @@ export function BaseChart({ labelPosition, stacked, smooth, + connectNulls, showSymbol, symbolSize, showArea, diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index dcc1ee5aa..005ab08b8 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -6,6 +6,7 @@ import { getTypeIdSets } from "@/js/arrow/lazy-arrow"; import { NAME_FIELD_PATTERNS } from "./constants"; import type { ChartData, + ChartValue, NormalizedChartData, NormalizedChartDataBase, Orientation, @@ -210,12 +211,13 @@ function extractFromJson( 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] = []; @@ -224,7 +226,12 @@ function extractFromJson( 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), + ); } } @@ -304,6 +311,8 @@ export function unknownKeysMessage( 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; } function isArrowTemporalField(table: Table, key: string): boolean { @@ -333,8 +342,11 @@ export function normalizeChartData( yKey, ); + const keepNulls = opts.keepNulls === true; const { xData: rawXData, yDataMap: rawYDataMap } = - ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys); + ArrowClient.extractChartData(table, resolvedXKey, resolvedYKeys, { + keepNulls, + }); const xAxisType: XAxisType = opts.xType ?? @@ -344,9 +356,9 @@ export function normalizeChartData( const chartType = xAxisType === "time" ? "timeseries" : "categorical"; 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] ?? [], keepNulls); } if (chartType === "timeseries") { @@ -392,12 +404,16 @@ export function normalizeChartData( 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 (chartType === "timeseries") { @@ -458,6 +474,7 @@ export function normalizeHeatmapData( xKey?: string, yAxisKey?: string, valueKey?: string | string[], + opts: { keepNulls?: boolean } = {}, ): NormalizedHeatmapData { // First, get the standard normalization const jsonData = isArrowTable(data) @@ -519,7 +536,10 @@ export function normalizeHeatmapData( for (const row of jsonData) { 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); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 92666d630..1f3a3c493 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -1,5 +1,10 @@ import { FALLBACK_UI_TOKENS } from "./constants"; -import type { ChartType, ChartUITokens, ChartValueFormatter } from "./types"; +import type { + ChartType, + ChartUITokens, + ChartValue, + ChartValueFormatter, +} from "./types"; import { createTimeSeriesData, escapeHtml, @@ -13,7 +18,7 @@ import { export interface OptionBuilderContext { xData: (string | number)[]; - yDataMap: Record; + yDataMap: Record; yFields: string[]; colors: string[]; title?: string; @@ -30,6 +35,8 @@ export interface CartesianContext extends OptionBuilderContext { isValueX?: boolean; stacked: boolean; smooth: boolean; + /** Draw line/area across `null` values instead of leaving a gap. */ + connectNulls?: boolean; showSymbol: boolean; symbolSize: number; /** @@ -464,6 +471,7 @@ export function buildCartesianOption( ? createTimeSeriesData(ctx.xData, ctx.yDataMap[key]) : ctx.yDataMap[key], smooth: isLineLike ? smooth : undefined, + connectNulls: isLineLike && ctx.connectNulls ? true : undefined, showSymbol: isLineLike ? showSymbol : undefined, symbol: isScatter ? "circle" : undefined, // Symbol size applies to line/area as well as scatter, so an interactive diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 1cec8f852..449825e6f 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -41,6 +41,9 @@ export type ChartType = | "radar" | "heatmap"; +/** One measure value after normalization; `null` is a gap (v3 defaults). */ +export type ChartValue = string | number | null; + /** Data that can be passed to unified charts */ export type ChartData = Table | Record[]; @@ -260,6 +263,11 @@ export interface LineChartSpecificProps { showSymbol?: boolean; /** Smooth line curves @default true */ smooth?: boolean; + /** + * Draw the line across missing values instead of leaving a gap. Only applies + * with `defaults="v3"`, where missing values stay missing. @default false + */ + connectNulls?: boolean; } /** Props specific to area charts */ @@ -270,6 +278,11 @@ export interface AreaChartSpecificProps { showSymbol?: boolean; /** Smooth line curves @default true */ smooth?: boolean; + /** + * Draw the line across missing values instead of leaving a gap. Only applies + * with `defaults="v3"`, where missing values stay missing. @default false + */ + connectNulls?: boolean; /** Stack areas @default false */ stacked?: boolean; } @@ -343,7 +356,7 @@ export interface NormalizedChartDataBase { /** Normalized chart data for rendering (standard charts) */ export interface NormalizedChartData extends NormalizedChartDataBase { - yDataMap: Record; + yDataMap: Record; } /** Type guard to check if data is an Arrow Table */ diff --git a/packages/appkit-ui/src/react/charts/utils.ts b/packages/appkit-ui/src/react/charts/utils.ts index 7e6d36bd2..5906bcd99 100644 --- a/packages/appkit-ui/src/react/charts/utils.ts +++ b/packages/appkit-ui/src/react/charts/utils.ts @@ -1,4 +1,4 @@ -import type { ChartClickDatum } from "./types"; +import type { ChartClickDatum, ChartValue } from "./types"; // ============================================================================ // Chart Utility Functions @@ -13,6 +13,14 @@ export function toChartValue(value: unknown): string | number { if (value === null || value === undefined) { return 0; } + return toChartValueOrNull(value) ?? 0; +} + +/** Like {@link toChartValue}, but keeps `null` and `undefined` as `null`. */ +function toChartValueOrNull(value: unknown): ChartValue { + if (value === null || value === undefined) { + return null; + } if (typeof value === "bigint") { return Number(value); } @@ -28,9 +36,11 @@ export function toChartValue(value: unknown): string | number { /** * Converts an array of values to chart-compatible types. */ -export function toChartArray(data: unknown[]): (string | number)[] { +export function toChartArray(data: unknown[]): (string | number)[]; +export function toChartArray(data: unknown[], keepNulls: boolean): ChartValue[]; +export function toChartArray(data: unknown[], keepNulls = false): ChartValue[] { if (data.length === 0) return []; - return data.map(toChartValue); + return data.map(keepNulls ? toChartValueOrNull : toChartValue); } export { formatLabel } from "@/js"; @@ -66,10 +76,10 @@ export function truncateLabel(value: string, maxLength = 15): string { */ export function createTimeSeriesData( xData: (string | number)[], - yData: (string | number)[], -): [string | number, string | number][] { + yData: ChartValue[], +): [string | number, ChartValue][] { const len = xData.length; - const result: [string | number, string | number][] = new Array(len); + const result: [string | number, ChartValue][] = new Array(len); for (let i = 0; i < len; i++) { result[i] = [xData[i], yData[i]]; } @@ -82,11 +92,11 @@ export function createTimeSeriesData( */ export function sortNumericAscending( xData: (string | number)[], - yDataMap: Record, + yDataMap: Record, yFields: string[], ): { xData: (string | number)[]; - yDataMap: Record; + yDataMap: Record; } { if (xData.length <= 1) { return { xData, yDataMap }; @@ -96,7 +106,7 @@ export function sortNumericAscending( indices.sort((a, b) => Number(xData[a]) - Number(xData[b])); const sortedXData = indices.map((i) => Number(xData[i])); - const sortedYDataMap: Record = {}; + const sortedYDataMap: Record = {}; for (const key of yFields) { const original = yDataMap[key]; sortedYDataMap[key] = indices.map((i) => original[i]); @@ -336,11 +346,11 @@ export function toChronologicalValue(value: unknown): number | null { */ export function sortTimeSeriesAscending( xData: (string | number)[], - yDataMap: Record, + yDataMap: Record, yFields: string[], ): { xData: (string | number)[]; - yDataMap: Record; + yDataMap: Record; } { if (xData.length <= 1) { return { xData, yDataMap }; @@ -362,7 +372,7 @@ export function sortTimeSeriesAscending( } const sortedXData = indices.map((i) => xData[i]); - const sortedYDataMap: Record = { + const sortedYDataMap: Record = { ...yDataMap, }; for (const key of yFields) { From bf3ac2b05d39bbcc234281f3883162aa8248187f Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:50:46 +0000 Subject: [PATCH 008/151] fix(appkit-ui): drop scatter points with a missing or non-numeric value Scatter handled missing values four ways: a null y was drawn at 0, a null x dropped the point, an empty-string y became 0 and a text y dropped the point. Scatter now keeps nulls through normalization and drops any point whose x or y is missing or not a number. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/options.test.ts | 22 +++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 3 +- .../appkit-ui/src/react/charts/options.ts | 32 +++++++++++++++++-- 3 files changed, 54 insertions(+), 3 deletions(-) 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 15c5920e8..7c34a1a89 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -1409,3 +1409,25 @@ describe("connectNulls (C2)", () => { expect(opt.series[0].connectNulls).toBe(true); }); }); + +describe("scatter missing values (SCAT-07)", () => { + 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], + ]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 7c11826a7..ea0bba338 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -304,7 +304,8 @@ export function BaseChart({ ? normalizeHeatmapData(data, xKey, yAxisKey, yKey, { keepNulls: v3 }) : normalizeChartData(data, xKey, yKey, orientation, { xType, - keepNulls: v3, + // Scatter drops points with a missing value instead of plotting 0. + keepNulls: v3 || chartType === "scatter", }), [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3], ); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 1f3a3c493..308788322 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -408,6 +408,33 @@ 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. + */ +function scatterPoints( + xData: (string | number)[], + yData: ChartValue[], +): [number, number][] { + const points: [number, number][] = []; + for (let i = 0; i < xData.length; i++) { + const x = toFiniteNumber(xData[i]); + const y = toFiniteNumber(yData[i]); + if (x !== null && y !== null) points.push([x, y]); + } + return points; +} + export function buildCartesianOption( ctx: CartesianContext, ): Record { @@ -464,8 +491,9 @@ export function buildCartesianOption( series: ctx.yFields.map((key, idx) => ({ name: formatLabel(key), type: seriesType, - data: - isScatter || isValueX + data: isScatter + ? scatterPoints(ctx.xData, ctx.yDataMap[key]) + : isValueX ? ctx.xData.map((x, i) => [x, ctx.yDataMap[key][i]]) : isTimeSeries ? createTimeSeriesData(ctx.xData, ctx.yDataMap[key]) From cdf0adf30ff7434f3b8a50c60848ea524d5d3210 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:51:18 +0000 Subject: [PATCH 009/151] fix(appkit-ui): leave non-numeric heatmap values empty and warn A heatmap value that is not a number ("high", true, "1,234.5") became 0 and pulled the color scale's minimum to 0. Such cells are now left empty, excluded from min and max, and a single console.warn names the value field and the first bad value. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 24 ++++++++++++++++++- .../appkit-ui/src/react/charts/normalize.ts | 19 ++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) 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 3117bd0b2..a210e17be 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"; @@ -674,3 +674,25 @@ describe("missing measures (C2, v3)", () => { expect(v3.xData).toEqual(["a", "b", "c"]); }); }); + +describe("heatmap non-numeric values (HM-03)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 005ab08b8..c837637d4 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -530,6 +530,7 @@ export function normalizeHeatmapData( // Build heatmap data and track min/max const heatmapData: [number, number, number][] = []; + const nonNumeric: unknown[] = []; let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; @@ -543,7 +544,17 @@ export function normalizeHeatmapData( 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]); @@ -552,6 +563,12 @@ export function normalizeHeatmapData( } } + if (nonNumeric.length > 0) { + console.warn( + `[appkit-ui] heatmap: ${nonNumeric.length} value(s) in "${resolvedValueKey}" are not numbers and were left empty (first: ${JSON.stringify(nonNumeric[0])}).`, + ); + } + // Handle edge case where no valid data was found if (heatmapData.length === 0) { min = 0; From 4a57cf7c00566afba4f6f9510dabf30fe848ee3b Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:52:55 +0000 Subject: [PATCH 010/151] fix(appkit-ui): read DATE strings as the viewer's calendar day, show dates without a time "2026-01-01" was parsed as UTC midnight and rendered in local time, so viewers west of UTC saw every point a day early and the tooltip read 2025-12-31 16:00:00. A DATE string (YYYY-MM-DD, no time) is now built as local midnight, so it is the same calendar day for every viewer, and impossible dates such as 2026-02-31 are rejected. When every x value is a DATE, the tooltip header shows the date without a time. Tested with TZ=America/Los_Angeles. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 19 ++++++ .../react/charts/__tests__/timezone.test.ts | 64 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 2 + .../appkit-ui/src/react/charts/normalize.ts | 5 ++ .../appkit-ui/src/react/charts/options.ts | 15 +++++ packages/appkit-ui/src/react/charts/types.ts | 2 + packages/appkit-ui/src/react/charts/utils.ts | 31 +++++++++ 7 files changed, 138 insertions(+) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts 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 58eb498ea..af23b1d58 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -360,3 +360,22 @@ describe("unknown keys (C3)", () => { expect(getByRole("alert").textContent).toContain('xKey "mnth"'); }); }); + +describe("date-only time axis (C6)", () => { + test("renders a DATE time axis without uncaught errors", async () => { + const { container } = render( + , + ); + await waitFor(() => + expect(container.querySelector("canvas")).not.toBeNull(), + ); + }); +}); 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..fd9a86df7 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts @@ -0,0 +1,64 @@ +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +import { normalizeChartData } from "../normalize"; +import { buildCartesianOption } 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 (C6)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index ea0bba338..6a653c802 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -318,6 +318,7 @@ export function BaseChart({ xField, chartType: detectedChartType, xAxisType, + xDateOnly, } = normalized; const isValueX = xAxisType === "value"; @@ -394,6 +395,7 @@ export function BaseChart({ chartType, isTimeSeries, isValueX: isValueX && !isHorizontal, + xDateOnly, stacked, smooth, connectNulls, diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index c837637d4..a77eb5a52 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -14,6 +14,7 @@ import type { } from "./types"; import { isArrowTable } from "./types"; import { + isDateOnlyColumn, sortNumericAscending, sortTimeSeriesAscending, toChartArray, @@ -382,6 +383,7 @@ export function normalizeChartData( yFields: resolvedYKeys, chartType, xAxisType, + xDateOnly: chartType === "timeseries" && isDateOnlyColumn(rawXData), }; } @@ -437,6 +439,9 @@ export function normalizeChartData( yFields: resolvedYKeys, chartType, xAxisType, + xDateOnly: + chartType === "timeseries" && + isDateOnlyColumn(columnValues(jsonData, resolvedXKey)), }; } diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 308788322..199785751 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -9,6 +9,7 @@ import { createTimeSeriesData, escapeHtml, formatLabel, + formatLocalDate, truncateLabel, } from "./utils"; @@ -33,6 +34,8 @@ export interface CartesianContext extends OptionBuilderContext { isTimeSeries: boolean; /** Plot x on a numeric value axis (`xType="value"`). */ isValueX?: boolean; + /** x holds DATE values: show dates without a time of day. */ + xDateOnly?: boolean; stacked: boolean; smooth: boolean; /** Draw line/area across `null` values instead of leaving a gap. */ @@ -472,6 +475,18 @@ export function buildCartesianOption( type: isScatter || isValueX ? "value" : isTimeSeries ? "time" : "category", data: isScatter || isValueX || isTimeSeries ? undefined : ctx.xData, + // Date-only data: the tooltip header shows the day, not midnight. + // (Omit the key otherwise: an explicit `undefined` breaks ECharts.) + ...(isTimeSeries && ctx.xDateOnly + ? { + axisPointer: { + label: { + formatter: (params: { value: number }) => + formatLocalDate(params.value), + }, + }, + } + : {}), name: ctx.xField ? formatLabel(ctx.xField) : undefined, ...mergeAxisLabel( ui, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 449825e6f..bc79e0b4f 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -352,6 +352,8 @@ export interface NormalizedChartDataBase { chartType: "timeseries" | "categorical"; /** Resolved x axis type, from `xType` or the `xKey` values. */ xAxisType?: XAxisType; + /** True when x holds DATE values (no time of day). */ + xDateOnly?: boolean; } /** Normalized chart data for rendering (standard charts) */ diff --git a/packages/appkit-ui/src/react/charts/utils.ts b/packages/appkit-ui/src/react/charts/utils.ts index 5906bcd99..d25df4ee6 100644 --- a/packages/appkit-ui/src/react/charts/utils.ts +++ b/packages/appkit-ui/src/react/charts/utils.ts @@ -317,6 +317,27 @@ export function mapToDatum( } const DATE_STRING_PATTERN = /^\d{4}-\d{2}-\d{2}(?:$|[T\s])/; +const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; + +/** True when every value is a DATE string (`YYYY-MM-DD`, no time). */ +export function isDateOnlyColumn(values: readonly unknown[]): boolean { + let present = 0; + for (const value of values) { + if (value === null || value === undefined || value === "") continue; + if (typeof value !== "string" || !DATE_ONLY_PATTERN.test(value)) { + return false; + } + present++; + } + return present > 0; +} + +/** Formats a timestamp as a local calendar date, `YYYY-MM-DD`. */ +export function formatLocalDate(timestamp: number): string { + const d = new Date(timestamp); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; +} /** * Converts a value to a number that can be compared chronologically, or null @@ -333,6 +354,16 @@ export function toChronologicalValue(value: unknown): number | null { if (typeof value !== "string") return null; if (!DATE_STRING_PATTERN.test(value)) return null; + // A DATE value has no time zone: it is the same calendar day for every + // viewer. `Date.parse("2026-01-01")` reads it as UTC midnight, which is the + // previous evening west of UTC, so build it as local midnight instead. + const dateOnly = DATE_ONLY_PATTERN.exec(value); + if (dateOnly) { + const [, y, m, d] = dateOnly; + const local = new Date(Number(y), Number(m) - 1, Number(d)); + return local.getMonth() === Number(m) - 1 ? local.getTime() : null; + } + // Spark JSON_ARRAY timestamps commonly use a space between the date and // time. Normalize that separator to the ISO form before parsing. const timestamp = Date.parse(value.replace(" ", "T")); From 0c759c045e6322e85a1c4bea419585a34d59351c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:53:26 +0000 Subject: [PATCH 011/151] fix(appkit-ui): read zone-less timestamps as wall-clock times, like DATE values One parser applied three timezone rules: DATE strings as UTC, zone-less timestamps (the Spark default) in the viewer's zone through engine-dependent Date.parse, and Z timestamps as absolute instants, so a DATE column and a DATE_TRUNC column disagreed for a US viewer. Zone-less timestamps (space or T separator, optional fractional seconds) are now parsed explicitly as wall-clock times in the viewer's zone, matching DATE values from C6; only values with Z or an offset are absolute. Tested with TZ=America/Los_Angeles. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/timezone.test.ts | 32 +++++++++++++++++++ packages/appkit-ui/src/react/charts/utils.ts | 22 +++++++++++++ 2 files changed, 54 insertions(+) diff --git a/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts index fd9a86df7..4a555783c 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts @@ -62,3 +62,35 @@ describe("DATE strings west of UTC (C6)", () => { expect(header).toBe("2026-01-01"); }); }); + +describe("one timezone rule (X7)", () => { + 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), + ); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/utils.ts b/packages/appkit-ui/src/react/charts/utils.ts index d25df4ee6..dbd7d5a7f 100644 --- a/packages/appkit-ui/src/react/charts/utils.ts +++ b/packages/appkit-ui/src/react/charts/utils.ts @@ -318,6 +318,9 @@ export function mapToDatum( const DATE_STRING_PATTERN = /^\d{4}-\d{2}-\d{2}(?:$|[T\s])/; const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; +/** A timestamp with no zone, e.g. Spark's default `2026-01-01 10:00:00.123456`. */ +const ZONELESS_TIMESTAMP_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?$/; /** True when every value is a DATE string (`YYYY-MM-DD`, no time). */ export function isDateOnlyColumn(values: readonly unknown[]): boolean { @@ -364,6 +367,25 @@ export function toChronologicalValue(value: unknown): number | null { return local.getMonth() === Number(m) - 1 ? local.getTime() : null; } + // A timestamp with no zone is a wall-clock time, read the same way as a + // DATE: in the viewer's zone, so DATE and DATE_TRUNC columns line up and the + // value renders the same for every viewer. Only a value with `Z` or an + // offset is an absolute instant. + const zoneless = ZONELESS_TIMESTAMP_PATTERN.exec(value); + if (zoneless) { + const [, y, m, d, hh, mm, ss = "0", frac = "0"] = zoneless; + const local = new Date( + Number(y), + Number(m) - 1, + Number(d), + Number(hh), + Number(mm), + Number(ss), + Number(frac.slice(0, 3).padEnd(3, "0")), + ); + return local.getMonth() === Number(m) - 1 ? local.getTime() : null; + } + // Spark JSON_ARRAY timestamps commonly use a space between the date and // time. Normalize that separator to the ISO form before parsing. const timestamp = Date.parse(value.replace(" ", "T")); From 36da34abed6219b56098edc76ceaceef5f5dfc9a Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:54:20 +0000 Subject: [PATCH 012/151] fix(appkit-ui): label dates on category axes and treat JS Date values as time Horizontal bars with a date xKey put epoch milliseconds on the category axis, and JS Date objects in rows became "Wed Dec 31 ..." category strings. Date objects are now time values (a time axis, sorted), and when time values sit on a category axis (horizontal bars) the labels and the tooltip header are formatted as YYYY-MM-DD, with HH:mm when the data has a time of day. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/timezone.test.ts | 53 ++++++++++++++++++- packages/appkit-ui/src/react/charts/base.tsx | 3 +- .../appkit-ui/src/react/charts/normalize.ts | 6 ++- .../appkit-ui/src/react/charts/options.ts | 23 ++++++-- packages/appkit-ui/src/react/charts/utils.ts | 15 ++++++ 5 files changed, 94 insertions(+), 6 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts index 4a555783c..d378b45b3 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/timezone.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from "vitest"; import { normalizeChartData } from "../normalize"; -import { buildCartesianOption } from "../options"; +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. @@ -94,3 +94,54 @@ describe("one timezone rule (X7)", () => { ); }); }); + +describe("dates on category axes (C10)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 6a653c802..46fb790c5 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -341,6 +341,8 @@ export function BaseChart({ xField, ui, valueFormatter, + xIsTime: detectedChartType === "timeseries", + xDateOnly, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -395,7 +397,6 @@ export function BaseChart({ chartType, isTimeSeries, isValueX: isValueX && !isHorizontal, - xDateOnly, stacked, smooth, connectNulls, diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index a77eb5a52..6b67a0fd9 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -73,7 +73,7 @@ function inferXType(values: readonly unknown[]): XAxisType { for (const value of values) { if (isMissing(value)) continue; present++; - if (!isDateString(value)) return "category"; + if (!(value instanceof Date) && !isDateString(value)) return "category"; } return present > 0 ? "time" : "category"; } @@ -181,6 +181,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); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 199785751..22513e10f 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -10,6 +10,7 @@ import { escapeHtml, formatLabel, formatLocalDate, + formatTimeLabel, truncateLabel, } from "./utils"; @@ -27,6 +28,10 @@ export interface OptionBuilderContext { xField?: string; ui?: ChartUITokens; valueFormatter?: ChartValueFormatter; + /** x holds timestamps drawn on a category axis (horizontal bars). */ + xIsTime?: boolean; + /** x holds DATE values (no time of day). */ + xDateOnly?: boolean; } export interface CartesianContext extends OptionBuilderContext { @@ -34,8 +39,6 @@ export interface CartesianContext extends OptionBuilderContext { isTimeSeries: boolean; /** Plot x on a numeric value axis (`xType="value"`). */ isValueX?: boolean; - /** x holds DATE values: show dates without a time of day. */ - xDateOnly?: boolean; stacked: boolean; smooth: boolean; /** Draw line/area across `null` values instead of leaving a gap. */ @@ -287,8 +290,22 @@ export function buildHorizontalBarOption( ...mergeAxisLabel(ui, { width: 100, overflow: "truncate", - formatter: (value: string) => truncateLabel(String(value)), + formatter: ctx.xIsTime + ? (value: string) => + formatTimeLabel(Number(value), ctx.xDateOnly === true) + : (value: string) => truncateLabel(String(value)), }), + // Dates on a category axis: format the tooltip header the same way. + ...(ctx.xIsTime + ? { + axisPointer: { + label: { + formatter: (params: { value: string | number }) => + formatTimeLabel(Number(params.value), ctx.xDateOnly === true), + }, + }, + } + : {}), }, series: ctx.yFields.map((key, idx) => ({ name: formatLabel(key), diff --git a/packages/appkit-ui/src/react/charts/utils.ts b/packages/appkit-ui/src/react/charts/utils.ts index dbd7d5a7f..1c4bab2db 100644 --- a/packages/appkit-ui/src/react/charts/utils.ts +++ b/packages/appkit-ui/src/react/charts/utils.ts @@ -335,6 +335,21 @@ export function isDateOnlyColumn(values: readonly unknown[]): boolean { return present > 0; } +/** + * Formats a timestamp for a category-axis label: the date, plus `HH:mm` when + * the data has a time of day. + */ +export function formatTimeLabel(timestamp: number, dateOnly: boolean): string { + const day = formatLocalDate(timestamp); + if (dateOnly) return day; + const d = new Date(timestamp); + if (d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0) { + return day; + } + const pad = (n: number) => String(n).padStart(2, "0"); + return `${day} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + /** Formats a timestamp as a local calendar date, `YYYY-MM-DD`. */ export function formatLocalDate(timestamp: number): string { const d = new Date(timestamp); From 34062ed60024bf213e642d36f3d6eaab0d441a6d Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:55:22 +0000 Subject: [PATCH 013/151] fix(appkit-ui): never rewrite or re-sort category values Category values that looked like numbers or dates were rewritten and re-sorted: "007", "010", "003" became 3, 7, 10, years were sorted ascending whatever the row order (until an Other row switched sorting off), and dates used as pie slice names or radar metrics showed as epoch milliseconds, so selected="007" matched nothing. Only a numeric axis (xType="value") is sorted now; category values keep their text and row order. Pie, donut and radar normalize x as categories unless xType is given. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 70 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 10 ++- .../appkit-ui/src/react/charts/normalize.ts | 18 ++++- 3 files changed, 95 insertions(+), 3 deletions(-) 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 a210e17be..6920aa1bb 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -696,3 +696,73 @@ describe("heatmap non-numeric values (HM-03)", () => { warn.mockRestore(); }); }); + +describe("category values are never rewritten or re-sorted (X3)", () => { + 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"]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 46fb790c5..9ce5be7c5 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -303,7 +303,15 @@ export function BaseChart({ chartType === "heatmap" ? normalizeHeatmapData(data, xKey, yAxisKey, yKey, { keepNulls: v3 }) : normalizeChartData(data, xKey, yKey, orientation, { - xType, + // 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. keepNulls: v3 || chartType === "scatter", }), diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 6b67a0fd9..259766ea9 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -372,7 +372,14 @@ export function normalizeChartData( yDataMap, resolvedYKeys, )); - } else if (xData.length > 0 && xData.every(isNumericValue)) { + } else if ( + xAxisType === "value" && + xData.length > 0 && + xData.every(isNumericValue) + ) { + // Only a numeric axis is sorted; category values keep their row order + // and their text ("007" stays "007"). + ({ xData, yDataMap } = sortNumericAscending( xData, yDataMap, @@ -428,7 +435,14 @@ export function normalizeChartData( yDataMap, resolvedYKeys, )); - } else if (xData.length > 0 && xData.every(isNumericValue)) { + } else if ( + xAxisType === "value" && + xData.length > 0 && + xData.every(isNumericValue) + ) { + // Only a numeric axis is sorted; category values keep their row order + // and their text ("007" stays "007"). + ({ xData, yDataMap } = sortNumericAscending( xData, yDataMap, From e131155ddd6791fb31fde9fe4c72216fd415170a Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:56:32 +0000 Subject: [PATCH 014/151] feat(appkit-ui): add seriesKey to plot long rows, warn on repeated x values Long rows (date, category, value), the shape SQL returns, could not be plotted: passed as they were they drew a sawtooth and a tooltip with the same name repeated. A seriesKey prop now pivots long rows during normalization: yKey is the single value column and each distinct seriesKey value becomes a series in first-appearance order; a missing combination is 0, or a gap with defaults="v3". Works for JSON and Arrow data. Bar, line and area charts without seriesKey now console.warn when an x value repeats, pointing at seriesKey. seriesKey is also checked by the unknown-key error state. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 36 ++++++++++ .../react/charts/__tests__/normalize.test.ts | 37 ++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 28 +++++++- .../appkit-ui/src/react/charts/normalize.ts | 71 +++++++++++++++++++ packages/appkit-ui/src/react/charts/types.ts | 6 ++ 5 files changed, 175 insertions(+), 3 deletions(-) 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 af23b1d58..24e8bc5c5 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -379,3 +379,39 @@ describe("date-only time axis (C6)", () => { ); }); }); + +describe("repeated x values (C7)", () => { + 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); + }); +}); 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 6920aa1bb..a8e89e7f5 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -766,3 +766,40 @@ describe("category values are never rewritten or re-sorted (X3)", () => { ).toEqual(["2026-01-01", "2026-02-01"]); }); }); + +describe("seriesKey pivots long rows (C7)", () => { + 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"]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 9ce5be7c5..d8efa11e3 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -130,6 +130,8 @@ export interface BaseChartProps { yKey?: string | string[]; /** 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; /** Chart orientation @default "vertical" */ orientation?: Orientation; /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */ @@ -217,6 +219,7 @@ export function BaseChart({ xKey, yKey, xType, + seriesKey, orientation, height, title, @@ -290,8 +293,8 @@ export function BaseChart({ // A key that is not in the rows would draw a flat zero series; report it. const keyError = useMemo( - () => unknownKeysMessage(data, { xKey, yKey, yAxisKey }), - [data, xKey, yKey, yAxisKey], + () => unknownKeysMessage(data, { xKey, yKey, yAxisKey, seriesKey }), + [data, xKey, yKey, yAxisKey, seriesKey], ); useEffect(() => { if (keyError) console.error(`[appkit-ui] ${chartType} chart: ${keyError}`); @@ -314,10 +317,29 @@ export function BaseChart({ : undefined), // Scatter drops points with a missing value instead of plotting 0. keepNulls: v3 || chartType === "scatter", + seriesKey, }), - [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3], + [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3, seriesKey], ); + // 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 { diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 259766ea9..32cc28516 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -318,6 +318,43 @@ export interface NormalizeOptions { 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. + */ +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) { + wide = { [xKey]: x }; + byX.set(xId, wide); + } + wide[series] = row[valueKey]; + } + return { rows: Array.from(byX.values()), seriesNames }; } function isArrowTemporalField(table: Table, key: string): boolean { @@ -337,6 +374,40 @@ export function normalizeChartData( 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], + ); + return normalizeChartData( + pivot.rows, + resolvedXKey, + pivot.seriesNames, + orientation, + { + ...opts, + seriesKey: undefined, + }, + ); + } + if (isArrowTable(data)) { const table = data as Table; const detected = ArrowClient.detectFieldsFromArrow(table, orientation); diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index bc79e0b4f..6f35d175d 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -115,6 +115,12 @@ export interface ChartBaseProps { xKey?: string; /** Y-axis field key(s). Auto-detected from schema if not provided. */ yKey?: string | 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. + */ + seriesKey?: string; /** * X axis type (cartesian charts). Inferred from the `xKey` values only, never * from column names: all dates gives `"time"`, otherwise `"category"`. From 866898d1f7c7f595dd86741fa7af5734e029e0a2 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:57:50 +0000 Subject: [PATCH 015/151] fix(appkit-ui): render an Arrow Table passed as data without prior Arrow loading An Arrow Table passed as data failed with "Failed to render chart" on every chart but the heatmap: field detection read Arrow type ids that were only initialized when a query result was fetched as Arrow. The type id sets now initialize on first use from the fixed Arrow Type ids (ARROW_TYPE_IDS, checked against apache-arrow in a test), so detection and extraction work on a Table the app built itself. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- packages/appkit-ui/src/js/arrow/lazy-arrow.ts | 110 +++++++++++++++--- .../react/charts/__tests__/arrow-data.test.ts | 48 ++++++++ .../appkit-ui/src/react/charts/normalize.ts | 6 +- 3 files changed, 143 insertions(+), 21 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts 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..09747fc02 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts @@ -0,0 +1,48 @@ +import { Type, tableFromArrays } from "apache-arrow"; +import { describe, expect, test } from "vitest"; + +import { ARROW_TYPE_IDS } from "@/js/arrow/lazy-arrow"; + +import { 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 (X1)", () => { + 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); + } + }); +}); diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 32cc28516..bb5d7303d 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -360,11 +360,7 @@ function pivotLongRows( function isArrowTemporalField(table: Table, key: string): boolean { const field = table.schema.fields.find((f) => f.name === key); if (!field) return false; - try { - return getTypeIdSets().temporal.has(field.typeId); - } catch { - return false; - } + return getTypeIdSets().temporal.has(field.typeId); } export function normalizeChartData( From 567d07542ab3338a8f03d594f50a07cbc862d8b8 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 20:59:17 +0000 Subject: [PATCH 016/151] fix(appkit-ui): type the chart transformer as rows in, rows out transformer was typed (data: T) => T, so it could not reshape rows without casts. It is now ChartTransformer, (rows: ChartRow[]) => ChartRow[], on chart props, ChartWrapper and useChartData. Arrow results are passed to it as plain rows, so one transformer works for both formats. Renaming DataTable's transform prop to match is left to the DataTable changes. BREAKING CHANGE: chart transformer is now (rows: ChartRow[]) => ChartRow[]; Arrow results reach it as plain rows, not an Arrow Table. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- packages/appkit-ui/src/react/charts/index.ts | 1 + packages/appkit-ui/src/react/charts/types.ts | 10 ++++-- .../appkit-ui/src/react/charts/wrapper.tsx | 6 ++-- .../hooks/__tests__/use-chart-data.test.ts | 32 ++++++++++++++++--- .../src/react/hooks/use-chart-data.ts | 18 ++++++++--- 5 files changed, 54 insertions(+), 13 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts index 6b4bcd5e4..c99fcdd2f 100644 --- a/packages/appkit-ui/src/react/charts/index.ts +++ b/packages/appkit-ui/src/react/charts/index.ts @@ -112,6 +112,7 @@ export type { ChartDataInput, ChartDefaults, ChartRow, + ChartTransformer, ChartType, ChartUITokens, ChartValueFormatter, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 6f35d175d..64d6ed481 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -50,6 +50,12 @@ export type ChartData = Table | Record[]; /** One row of chart data (indexable, to type plain data modules). */ export type ChartRow = Record; +/** + * Reshapes query rows before the chart reads them: rows in, rows out. It may + * add, rename, drop or aggregate columns. Arrow results are passed as rows. + */ +export type ChartTransformer = (rows: ChartRow[]) => ChartRow[]; + /** A chart's `data`: an Arrow Table, or rows (interfaces and `as const` arrays too). */ export type ChartDataInput = Table | readonly object[]; @@ -220,8 +226,8 @@ export interface QueryProps extends ChartBaseProps { * @default "auto" */ format?: DataFormat; - /** Transform raw data before rendering */ - transformer?: (data: T) => T; + /** Reshape the fetched rows before rendering. See {@link ChartTransformer}. */ + transformer?: ChartTransformer; // Discriminator: cannot use direct data with query data?: never; } diff --git a/packages/appkit-ui/src/react/charts/wrapper.tsx b/packages/appkit-ui/src/react/charts/wrapper.tsx index 3b5ef24a0..aef001ea9 100644 --- a/packages/appkit-ui/src/react/charts/wrapper.tsx +++ b/packages/appkit-ui/src/react/charts/wrapper.tsx @@ -7,7 +7,7 @@ import { chartSizeStyle } from "./constants"; import { EmptyState } from "./empty"; import { ErrorState } from "./error"; import { LoadingSkeleton, ResourceWaitingPlaceholder } from "./loading"; -import type { ChartData, DataFormat } from "./types"; +import type { ChartData, ChartTransformer, DataFormat } from "./types"; import { isArrowTable } from "./types"; const WAREHOUSE_ERROR_STATES = new Set(["DELETED", "DELETING"]); @@ -38,8 +38,8 @@ interface ChartWrapperQueryProps { parameters?: Record; /** Data format preference */ format?: DataFormat; - /** Transform data after fetching */ - transformer?: (data: T) => T; + /** Reshape the fetched rows. See {@link ChartTransformer}. */ + transformer?: ChartTransformer; /** Direct data - not used in query mode */ data?: never; } diff --git a/packages/appkit-ui/src/react/hooks/__tests__/use-chart-data.test.ts b/packages/appkit-ui/src/react/hooks/__tests__/use-chart-data.test.ts index 686aff317..ef91f425f 100644 --- a/packages/appkit-ui/src/react/hooks/__tests__/use-chart-data.test.ts +++ b/packages/appkit-ui/src/react/hooks/__tests__/use-chart-data.test.ts @@ -392,10 +392,10 @@ describe("useChartData", () => { error: null, }); - const transformer = vi.fn((data: T): T => { - const arr = data as { value: number }[]; - return arr.map((d) => ({ ...d, doubled: d.value * 2 })) as T; - }); + // Rows in, rows out: a reshape needs no casts. + const transformer = vi.fn((rows: Record[]) => + rows.map((d) => ({ ...d, doubled: Number(d.value) * 2 })), + ); const { result } = renderHook(() => useChartData({ @@ -445,6 +445,30 @@ describe("useChartData", () => { consoleSpy.mockRestore(); }); + test("passes Arrow results to the transformer as rows (C29)", async () => { + const { tableFromArrays } = await import("apache-arrow"); + const table = tableFromArrays({ + region: ["east", "west"], + revenue: Float64Array.from([1, 2]), + }); + mockUseAnalyticsQuery.mockReturnValue({ + data: table, + loading: false, + error: null, + }); + const transformer = vi.fn((rows: Record[]) => + rows.filter((r) => r.region === "west"), + ); + const { result } = renderHook(() => + useChartData({ queryKey: "test", transformer }), + ); + expect(transformer).toHaveBeenCalledWith([ + { region: "east", revenue: 1 }, + { region: "west", revenue: 2 }, + ]); + expect(result.current.data).toEqual([{ region: "west", revenue: 2 }]); + }); + test("does not apply transformer when data is null", () => { mockUseAnalyticsQuery.mockReturnValue({ data: null, diff --git a/packages/appkit-ui/src/react/hooks/use-chart-data.ts b/packages/appkit-ui/src/react/hooks/use-chart-data.ts index 4f98527b2..0d0f029f3 100644 --- a/packages/appkit-ui/src/react/hooks/use-chart-data.ts +++ b/packages/appkit-ui/src/react/hooks/use-chart-data.ts @@ -1,7 +1,13 @@ import type { Table } from "apache-arrow"; import { useMemo } from "react"; -import type { ChartData, DataFormat } from "../charts/types"; +import type { + ChartData, + ChartRow, + ChartTransformer, + DataFormat, +} from "../charts/types"; +import { isArrowTable } from "../charts/types"; import type { WarehouseStatus } from "./types"; import { useAnalyticsQuery } from "./use-analytics-query"; @@ -25,8 +31,8 @@ export interface UseChartDataOptions { * @default "auto" */ format?: DataFormat; - /** Transform data after fetching */ - transformer?: (data: T) => T; + /** Reshape the fetched rows (rows in, rows out). Arrow results arrive as rows. */ + transformer?: ChartTransformer; } export interface UseChartDataResult { @@ -140,7 +146,11 @@ export function useChartData(options: UseChartDataOptions): UseChartDataResult { // Apply transformer if provided if (transformer) { try { - return transformer(rawData); + const data = rawData as ChartData; + const rows: ChartRow[] = isArrowTable(data) + ? Array.from(data, (row) => ({ ...row.toJSON() })) + : (data as ChartRow[]); + return transformer(rows); } catch (err) { console.error("[useChartData] Transformer error:", err); return rawData; From f8fbbe9b4aec2b215602473247fe93fbfa91d5db Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:00:57 +0000 Subject: [PATCH 017/151] fix(appkit-ui): detect chart fields with one path for Arrow and JSON rows Arrow results went through ArrowClient.detectFieldsFromArrow, which had its own rules (string columns named date/time/period counted as dates, metadata dates were ranked differently, first-row checks differed), so the same query could chart differently depending on whether format="auto" picked Arrow (it does when parameters include startDate and endDate, or a limit above 500). Charts now use one detectFields function for both: an Arrow column's declared type is used when known, and otherwise the same value rules apply; names only rank candidates. Choosing the format from the actual result size needs the analytics server to report it before the client picks a format, so that part is not in this change; ArrowClient.detectFieldsFromArrow is kept for API compatibility. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/arrow-data.test.ts | 45 ++++++ .../appkit-ui/src/react/charts/normalize.ts | 142 +++++++++++++----- 2 files changed, 152 insertions(+), 35 deletions(-) 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 index 09747fc02..dff4cb981 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/arrow-data.test.ts @@ -46,3 +46,48 @@ describe("Arrow Table as data (X1)", () => { } }); }); + +describe("one detection path for Arrow and JSON (C28)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index bb5d7303d..ae57006a1 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -3,7 +3,7 @@ import type { Table } from "apache-arrow"; import { ArrowClient } from "@/js"; import { getTypeIdSets } from "@/js/arrow/lazy-arrow"; -import { NAME_FIELD_PATTERNS } from "./constants"; +import { METADATA_DATE_PATTERNS, NAME_FIELD_PATTERNS } from "./constants"; import type { ChartData, ChartValue, @@ -86,57 +86,85 @@ function columnValues(data: Record[], key: string): unknown[] { // 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); - - // Date fields are decided by their values, never by their names: a measure - // named `avg_response_time` is not a date. - const dateFields = keys.filter( - (key) => inferXType(columnValues(data, key)) === "time", - ); - - // Detect name/category fields by pattern AND value type - let nameFields = keys.filter((key) => { - const value = firstRow[key]; + 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 ( - isCategoryValue(value) && - !isDateString(value) && - NAME_FIELD_PATTERNS.some((p) => key.toLowerCase().includes(p)) + !dateFields.includes(key) && + isCategoryValue(firstPresent(source.values(key))) ); - }); + }; + + // Detect name/category fields by pattern AND value type + 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"; @@ -160,6 +188,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 // ============================================================================ @@ -406,7 +478,7 @@ export function normalizeChartData( if (isArrowTable(data)) { const table = data as Table; - const detected = ArrowClient.detectFieldsFromArrow(table, orientation); + const detected = detectFieldsFromTable(table, orientation); const { resolvedXKey, resolvedYKeys } = resolveKeys( detected, table.schema.fields.map((f) => f.name), From 84521f9f44b05b9c87ed77d17a81fe7f03c2b41c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:03:41 +0000 Subject: [PATCH 018/151] fix(appkit-ui): deep-merge custom chart options and accept a function options was spread one level deep, so xAxis/yAxis/series/grid/legend/tooltip replaced the built objects: a label-rotation tweak turned the category axis into a value axis and a markLine series entry removed every series. Objects are now deep-merged, with series, axes, grid, dataZoom and visualMap merged entry by entry (an object patch applies to every entry). options can also be a function (built) => next. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/options.test.ts | 57 ++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 10 ++- .../appkit-ui/src/react/charts/options.ts | 87 +++++++++++++++++++ packages/appkit-ui/src/react/charts/types.ts | 11 ++- 4 files changed, 161 insertions(+), 4 deletions(-) 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 7c34a1a89..8eab208ed 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"; @@ -1431,3 +1432,59 @@ describe("scatter missing values (SCAT-07)", () => { ]); }); }); + +describe("mergeChartOptions (C4)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index d8efa11e3..2bde64368 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -41,6 +41,8 @@ import { buildHorizontalBarOption, buildPieOption, buildRadarOption, + type ChartOptionsInput, + mergeChartOptions, type OptionBuilderContext, } from "./options"; import { useChartUITokens, useThemeColors } from "./theme"; @@ -183,8 +185,12 @@ export interface BaseChartProps { * 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 */ @@ -437,7 +443,7 @@ export function BaseChart({ } // Apply selection after custom options; empty selection is a no-op. - const merged = customOptions ? { ...opt, ...customOptions } : opt; + const merged = mergeChartOptions(opt, customOptions); return applySelectionEmphasis(merged, selected); }, [ normalized, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 22513e10f..eb9c23a4a 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -554,6 +554,93 @@ export function buildCartesianOption( }; } +// ============================================================================ +// 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 { + const out: Record = { ...base }; + for (const [key, value] of Object.entries(patch)) { + const prev = base[key]; + if (INDEXED_KEYS.has(key)) { + out[key] = mergeIndexed(prev, value); + } else if (isPlainObject(prev) && isPlainObject(value)) { + out[key] = deepMerge(prev, value); + } else { + out[key] = value; + } + } + return out; +} + +/** + * Merges a component list (`series`, axes, grids) entry by entry, so a patch + * for the first series or axis keeps the built data, type and styling. + */ +function mergeIndexed(prev: unknown, value: unknown): unknown { + const prevList = Array.isArray(prev) + ? prev + : prev === undefined + ? [] + : [prev]; + if (isPlainObject(value)) { + if (Array.isArray(prev)) { + return prev.map((item) => + isPlainObject(item) ? deepMerge(item, value) : value, + ); + } + return isPlainObject(prev) ? deepMerge(prev, value) : value; + } + if (!Array.isArray(value)) return value; + const length = Math.max(prevList.length, value.length); + const merged: unknown[] = []; + for (let i = 0; i < length; i++) { + const a = prevList[i]; + const b = value[i]; + if (b === undefined) merged.push(a); + else if (isPlainObject(a) && isPlainObject(b)) merged.push(deepMerge(a, b)); + else merged.push(b); + } + // A single built axis stays an object when one patch entry targets it. + return !Array.isArray(prev) && merged.length === 1 ? merged[0] : merged; +} + +/** + * Applies custom `options` to a built ECharts option. Objects are deep-merged + * (series and axes by index); a function receives the built option and + * returns the next one. + */ +export function mergeChartOptions( + built: Record, + custom: ChartOptionsInput | undefined, +): Record { + if (!custom) return built; + if (typeof custom === "function") return custom(built); + return deepMerge(built, custom); +} + // ============================================================================ // Selection Emphasis (declarative cross-filter highlighting) // ============================================================================ diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 64d6ed481..09695b20c 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -144,8 +144,15 @@ export interface ChartBaseProps { /** Test ID for automated testing */ testId?: string; - /** Additional ECharts options to merge */ - options?: 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. + */ + options?: + | Record + | ((built: Record) => Record); /** * `(value: string | number, field: string) => string`. Formats measure values in the chart's built-in value From c2769f7e81792a4848fcc11dd54963fc11147d9c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:04:14 +0000 Subject: [PATCH 019/151] test(appkit-ui): partial radar options keep the metric list Fixed by the C4 deep merge: options={{ radar: {...} }} without an indicator list used to replace the built radar object, blank the chart and throw a TypeError. The test mounts a radar with a partial radar option and checks the indicators survive. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) 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 24e8bc5c5..dca2cf3ca 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -415,3 +415,39 @@ describe("repeated x values (C7)", () => { ).toBe(false); }); }); + +describe("radar options (RAD-01)", () => { + 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([]); + }); +}); From 1e0429b84e670a489631c7c7c420fe650f0bbdc4 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:05:18 +0000 Subject: [PATCH 020/151] fix(appkit-ui): replace the chart option on update so removed series disappear ECharts was updated in merge mode, so series, legend entries and axes that a new option no longer had stayed on the chart (three lines remained after yKey went from three keys to one). BaseChart now passes notMerge so every update replaces the option. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 33 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 4 ++- 2 files changed, 36 insertions(+), 1 deletion(-) 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 dca2cf3ca..f1eafdcb0 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -451,3 +451,36 @@ describe("radar options (RAD-01)", () => { expect(pageErrors).toEqual([]); }); }); + +describe("updates after mount (C5)", () => { + 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); + }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 2bde64368..5f4553979 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -542,7 +542,9 @@ export function BaseChart({ style={chartSizeStyle(height)} className={className} opts={{ renderer: "canvas" }} - notMerge={false} + // Replace the option on every update: in merge mode, series, legend + // entries and axes that the new option no longer has stay on the chart. + notMerge={true} lazyUpdate={true} onEvents={onEvents} /> From e3613763520d108cb258c0552ba5247661193b6e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:05:56 +0000 Subject: [PATCH 021/151] fix(appkit-ui): stack vertical bars when stacked is set stacked only reached horizontal bars and areas; vertical bar series had no stack, so stacked bars drew side by side. Bar series now get the same stack as areas. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 35 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 5 ++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts 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..d50ac3e7c --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "vitest"; + +import { buildCartesianOption, type CartesianContext } 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 (C8)", () => { + 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]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index eb9c23a4a..6e353fe89 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -541,7 +541,10 @@ export function buildCartesianOption( // 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, + stack: + stacked && (chartType === "area" || chartType === "bar") + ? "total" + : undefined, itemStyle: chartType === "bar" ? { borderRadius: [4, 4, 0, 0] } : undefined, color: ctx.colors[idx % ctx.colors.length], From 4c4e15828cbf257a3ea4387ba026a40bc65a7f76 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:07:18 +0000 Subject: [PATCH 022/151] fix(appkit-ui): drop orientation from LineChart and AreaChart orientation="horizontal" on a LineChart or AreaChart rendered a bar chart. The prop is removed from the line and area types, and BaseChart ignores orientation for every chart type except bar. BREAKING CHANGE: LineChart and AreaChart no longer accept orientation; use BarChart for horizontal bars. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 29 +++++++++++++++++++ .../src/react/charts/__tests__/types.test.ts | 19 ++++++++++-- packages/appkit-ui/src/react/charts/base.tsx | 7 +++-- packages/appkit-ui/src/react/charts/types.ts | 4 --- 4 files changed, 51 insertions(+), 8 deletions(-) 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 f1eafdcb0..02429e15e 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -484,3 +484,32 @@ describe("updates after mount (C5)", () => { }); }); }); + +describe("orientation on line and area (C9)", () => { + 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"); + }, + ); +}); 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..09c0a1daa 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 (C9)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 5f4553979..909d1e3ee 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -134,7 +134,7 @@ export interface BaseChartProps { xType?: XAxisType; /** Column naming the series in long rows. See {@link ChartBaseProps.seriesKey}. */ seriesKey?: string; - /** Chart orientation @default "vertical" */ + /** Bar orientation. Ignored by every other chart type. */ orientation?: Orientation; /** Chart height in pixels. Defaults to filling its parent (see `chartSizeStyle`). */ height?: number; @@ -226,7 +226,7 @@ export function BaseChart({ yKey, xType, seriesKey, - orientation, + orientation: orientationProp, height, title, showLegend = true, @@ -252,6 +252,9 @@ export function BaseChart({ defaults, }: BaseChartProps) { const v3 = defaults === "v3"; + // 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); const themeColors = useThemeColors(resolvedPalette); diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 09695b20c..9b80a6119 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -276,8 +276,6 @@ export interface BarChartSpecificProps { /** Props specific to line charts */ export interface LineChartSpecificProps { - /** Chart orientation @default "vertical" */ - orientation?: Orientation; /** Show data point symbols @default false */ showSymbol?: boolean; /** Smooth line curves @default true */ @@ -291,8 +289,6 @@ export interface LineChartSpecificProps { /** Props specific to area charts */ export interface AreaChartSpecificProps { - /** Chart orientation @default "vertical" */ - orientation?: Orientation; /** Show data point symbols @default false */ showSymbol?: boolean; /** Smooth line curves @default true */ From 23adbfe0a57bccc7c0e2d5f2595fd825f1da5fd6 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:09:23 +0000 Subject: [PATCH 023/151] fix(appkit-ui): type symbolSize on line/area and warn on ignored chart props symbolSize works on LineChart and AreaChart but was missing from their types, so typed code could not set it. In the other direction, every chart accepted every other chart prop at runtime and ignored it (min and max on a radar). The line and area types now have symbolSize, and in development each chart warns once about props its chart type ignores. The per-chart prop lists are type-checked against the prop interfaces so they cannot drift. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 57 +++++++++ .../charts/__tests__/helpers/echarts-env.ts | 57 +++++++++ .../src/react/charts/create-chart.tsx | 114 +++++++++++++++++- packages/appkit-ui/src/react/charts/types.ts | 4 + 4 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx create mode 100644 packages/appkit-ui/src/react/charts/__tests__/helpers/echarts-env.ts 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..83f278d81 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -0,0 +1,57 @@ +import { cleanup, render, waitFor } from "@testing-library/react"; +import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"; + +import { AreaChart } from "../area"; +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 (X8)", () => { + 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, max: 100 } as Record; + render( + , + ); + expect( + warn.mock.calls.some((c) => + String(c[0]).includes("RadarChart ignores `min`, `max`"), + ), + ).toBe(true); + }); +}); 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/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index d040257ba..5089a9af5 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -1,7 +1,118 @@ import { BaseChart } from "./base"; -import type { ChartData, ChartType, UnifiedChartProps } from "./types"; +import type { + AreaChartSpecificProps, + BarChartSpecificProps, + ChartBaseProps, + ChartData, + ChartType, + HeatmapChartSpecificProps, + LineChartSpecificProps, + PieChartSpecificProps, + RadarChartSpecificProps, + ScatterChartSpecificProps, + UnifiedChartProps, +} from "./types"; 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", +]; + +const PIE_PROPS = allKeys()([ + "innerRadius", + "showLabels", + "labelPosition", +]); + +/** Props each chart type reads, beyond the shared ones. */ +const CHART_PROPS: Record = { + bar: allKeys()(["orientation", "stacked"]), + line: allKeys()([ + "symbolSize", + "showSymbol", + "smooth", + "connectNulls", + ]), + area: allKeys()([ + "symbolSize", + "showSymbol", + "smooth", + "connectNulls", + "stacked", + ]), + scatter: allKeys()(["symbolSize"]), + pie: PIE_PROPS, + donut: PIE_PROPS, + radar: allKeys()(["showArea"]), + heatmap: allKeys()([ + "yAxisKey", + "min", + "max", + "showLabels", + ]), +}; + +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 +132,7 @@ export function createChart( displayName: string, ) { const Component = (props: TProps) => { + warnUnknownProps(chartType, displayName, props); const { // Query props queryKey, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 9b80a6119..06515de59 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -276,6 +276,8 @@ export interface BarChartSpecificProps { /** Props specific to line charts */ export interface LineChartSpecificProps { + /** Size of the data point symbols @default 8 */ + symbolSize?: number; /** Show data point symbols @default false */ showSymbol?: boolean; /** Smooth line curves @default true */ @@ -289,6 +291,8 @@ export interface LineChartSpecificProps { /** Props specific to area charts */ export interface AreaChartSpecificProps { + /** Size of the data point symbols @default 8 */ + symbolSize?: number; /** Show data point symbols @default false */ showSymbol?: boolean; /** Smooth line curves @default true */ From 2139a5e17afeaa3dc7e491a66176866c5e68808f Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:11:16 +0000 Subject: [PATCH 024/151] fix(appkit-ui): honour className heights and default to 300 px under v3 The wrapper and the chart both set an inline height: 100%, so className="h-[400px]" had no effect and a chart in a parent without a definite height was 160 px. For everyone: when className has a height utility (h-*, size-*, with variants), no inline height is set. With defaults="v3", the fill-parent minimum is 300 px instead of 160 px. Loading and waiting states keep the className so they hold the same box. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/sizing.test.tsx | 45 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 13 ++++-- .../appkit-ui/src/react/charts/constants.ts | 33 ++++++++++---- .../src/react/charts/create-chart.tsx | 14 +++++- packages/appkit-ui/src/react/charts/types.ts | 6 ++- .../appkit-ui/src/react/charts/wrapper.tsx | 25 ++++++++--- 6 files changed, 116 insertions(+), 20 deletions(-) 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..47740689f 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,48 @@ describe("ChartWrapper sizing", () => { expect(box.style.minHeight).toBe(""); }); }); + +describe("className heights and v3 default height (C11)", () => { + 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).toBe(""); + }); + + test.each(["md:h-96", "size-80", "rounded h-[18rem] p-2"])( + "%s counts as a className height", + (className) => { + expect(chartSizeStyle(undefined, { className })).toEqual({}); + }, + ); + + 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 }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 909d1e3ee..5d4d429f2 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -136,7 +136,11 @@ export interface BaseChartProps { seriesKey?: string; /** Bar orientation. Ignored by every other chart type. */ 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; @@ -252,6 +256,7 @@ export function BaseChart({ defaults, }: BaseChartProps) { const v3 = defaults === "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; @@ -519,7 +524,7 @@ export function BaseChart({
{keyError}
@@ -530,7 +535,7 @@ export function BaseChart({ return (
No data
@@ -542,7 +547,7 @@ export function BaseChart({ ref={chartRefCallback} echarts={echarts} option={option} - style={chartSizeStyle(height)} + style={sizeStyle} className={className} opts={{ renderer: "canvas" }} // Replace the option on every update: in merge mode, series, legend diff --git a/packages/appkit-ui/src/react/charts/constants.ts b/packages/appkit-ui/src/react/charts/constants.ts index 8eda4ac0f..559791c84 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,32 @@ 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 }; + if (opts.className && CLASS_HEIGHT_PATTERN.test(opts.className)) return {}; + return { + height: "100%", + minHeight: opts.defaults === "v3" ? CHART_V3_MIN_HEIGHT : CHART_MIN_HEIGHT, + }; } diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index 5089a9af5..b5fec7b0b 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -4,6 +4,7 @@ import type { BarChartSpecificProps, ChartBaseProps, ChartData, + ChartDefaults, ChartType, HeatmapChartSpecificProps, LineChartSpecificProps, @@ -146,6 +147,7 @@ export function createChart( className, ariaLabel, testId, + defaults, // All remaining props pass through to BaseChart ...chartProps } = props as TProps & { @@ -158,13 +160,21 @@ export function createChart( className?: string; ariaLabel?: string; testId?: string; + defaults?: ChartDefaults; }; 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, + height, + className, + ariaLabel, + testId, + defaults, + } : { queryKey: queryKey as string, parameters, @@ -174,6 +184,7 @@ export function createChart( className, ariaLabel, testId: testId ?? `${chartType}-chart-${queryKey}`, + defaults, }; return ( @@ -184,6 +195,7 @@ export function createChart( chartType={chartType} height={height} className={className} + defaults={defaults} {...chartProps} /> )} diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 06515de59..0fe3fdac7 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -112,7 +112,11 @@ export interface ChartBaseProps { * sequential and diverging palettes), held to the same formats. */ colors?: string[]; - /** 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; /** Additional CSS classes */ className?: string; diff --git a/packages/appkit-ui/src/react/charts/wrapper.tsx b/packages/appkit-ui/src/react/charts/wrapper.tsx index aef001ea9..329bbcc92 100644 --- a/packages/appkit-ui/src/react/charts/wrapper.tsx +++ b/packages/appkit-ui/src/react/charts/wrapper.tsx @@ -7,7 +7,12 @@ import { chartSizeStyle } from "./constants"; import { EmptyState } from "./empty"; import { ErrorState } from "./error"; import { LoadingSkeleton, ResourceWaitingPlaceholder } from "./loading"; -import type { ChartData, ChartTransformer, DataFormat } from "./types"; +import type { + ChartData, + ChartDefaults, + ChartTransformer, + DataFormat, +} from "./types"; import { isArrowTable } from "./types"; const WAREHOUSE_ERROR_STATES = new Set(["DELETED", "DELETING"]); @@ -63,6 +68,8 @@ interface CommonProps { ariaLabel?: string; /** Test ID for automated testing */ testId?: string; + /** Opt into the v3 defaults (300 px minimum height). */ + defaults?: ChartDefaults; /** Render function receiving the chart data */ children: (data: ChartData) => ReactNode; } @@ -83,8 +90,10 @@ function QueryModeContent({ className, ariaLabel, testId, + defaults, children, }: CommonProps & ChartWrapperQueryProps) { + const sizeStyle = chartSizeStyle(height, { className, defaults }); const { data, loading, error, isEmpty, warehouseStatus } = useChartData({ queryKey, parameters, @@ -94,14 +103,14 @@ function QueryModeContent({ if (isWarehouseWaiting(loading, data, warehouseStatus)) { return ( -
+
); } if (loading) { return ( -
+
); @@ -115,7 +124,7 @@ function QueryModeContent({ >
{children} @@ -217,6 +229,7 @@ export function ChartWrapper(props: ChartWrapperProps) { className={className} ariaLabel={ariaLabel} testId={testId} + defaults={defaults} > {children} From 3535c6fa6f949cfb1709dbb5ee59c6fb75fe91f5 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:12:17 +0000 Subject: [PATCH 025/151] fix(appkit-ui): pick bar orientation from the data under v3 and document the rule A BarChart with categories and no orientation is horizontal, while the types and docs said the default is vertical. The prop docs now state the real rule. With defaults="v3", a BarChart without orientation is vertical for dates, numbers (such as years) and up to 7 labels of at most 10 characters, and horizontal otherwise. Without v3 the current rule is unchanged. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../charts/__tests__/bar-orientation.test.tsx | 69 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 31 +++++++-- packages/appkit-ui/src/react/charts/types.ts | 7 +- 3 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx 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..4e5a5996f --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx @@ -0,0 +1,69 @@ +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 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 (C12)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 5d4d429f2..ffa93e0e6 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -117,6 +117,28 @@ function getDefaultPalette(chartType: ChartType): ChartColorPalette { } } +// ============================================================================ +// 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 // ============================================================================ @@ -134,7 +156,7 @@ export interface BaseChartProps { xType?: XAxisType; /** Column naming the series in long rows. See {@link ChartBaseProps.seriesKey}. */ seriesKey?: string; - /** Bar orientation. Ignored by every other chart type. */ + /** Bar orientation (see `BarChartSpecificProps`). Ignored by other chart types. */ orientation?: Orientation; /** * Chart height in pixels. Without it the chart fills its parent, at least @@ -395,10 +417,11 @@ export function BaseChart({ !isRadar && !isHeatmap && (orientation === "horizontal" || - (detectedChartType === "categorical" && + (!orientation && + chartType === "bar" && + detectedChartType === "categorical" && !isValueX && - !orientation && - chartType === "bar")); + (!v3 || !fitsVerticalBars(xData)))); const isTimeSeries = detectedChartType === "timeseries" && !isHorizontal && diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 0fe3fdac7..19001f4f9 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -272,7 +272,12 @@ export type UnifiedChartProps = QueryProps | DataProps; /** Props specific to bar charts */ export interface BarChartSpecificProps { - /** Chart orientation @default "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. + */ orientation?: Orientation; /** Stack bars */ stacked?: boolean; From 50c359f430a7a59db49cda8387c286b356b2183e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:12:36 +0000 Subject: [PATCH 026/151] test(appkit-ui): years without orientation render vertical under v3 Covered by the C12 orientation rule: a numeric x such as a year, with orientation unset, used to render horizontal with the oldest year at the bottom. With defaults="v3" numbers are vertical. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/bar-orientation.test.tsx | 7 +++++++ 1 file changed, 7 insertions(+) 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 index 4e5a5996f..14d44f5be 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/bar-orientation.test.tsx @@ -35,6 +35,7 @@ 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, @@ -67,3 +68,9 @@ describe("bar orientation without the prop (C12)", () => { expect(await isHorizontal(days, "day", "v3")).toBe(false); }); }); + +describe("numeric x such as years (BAR-07)", () => { + test("v3: years render vertical", async () => { + expect(await isHorizontal(years, "year", "v3")).toBe(false); + }); +}); From eb9956981e7a2bc0e5a818f8e5099d53b020c90e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:13:13 +0000 Subject: [PATCH 027/151] fix(appkit-ui): put the first row on top of horizontal bars under v3 Horizontal bars drew the first row at the bottom, so ORDER BY value DESC showed the smallest bar on top. With defaults="v3" the category axis is inverted so the first row is the top bar. Option builders now receive a v3 flag in their context. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 30 ++++++++++++++++++- packages/appkit-ui/src/react/charts/base.tsx | 2 ++ .../appkit-ui/src/react/charts/options.ts | 5 ++++ 3 files changed, 36 insertions(+), 1 deletion(-) 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 index d50ac3e7c..79780dbb9 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from "vitest"; -import { buildCartesianOption, type CartesianContext } from "../options"; +import { + buildCartesianOption, + buildHorizontalBarOption, + type CartesianContext, +} from "../options"; type Series = Record; type Option = { series: Series[]; [key: string]: unknown }; @@ -33,3 +37,27 @@ describe("vertical stacked bars (C8)", () => { expect(option.series.map((s) => s.stack)).toEqual([undefined, undefined]); }); }); + +describe("horizontal bar row order (C13)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index ffa93e0e6..ab3fd5417 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -409,6 +409,7 @@ export function BaseChart({ valueFormatter, xIsTime: detectedChartType === "timeseries", xDateOnly, + v3, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -499,6 +500,7 @@ export function BaseChart({ valueFormatter, selected, interactive, + v3, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 6e353fe89..2bc7831fc 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -32,6 +32,8 @@ export interface OptionBuilderContext { xIsTime?: boolean; /** x holds DATE values (no time of day). */ xDateOnly?: boolean; + /** Build with the `defaults="v3"` defaults. */ + v3?: boolean; } export interface CartesianContext extends OptionBuilderContext { @@ -287,6 +289,9 @@ export function buildHorizontalBarOption( 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, overflow: "truncate", From ac4d7f7caa5eda67f515745060a47e70c87dd83c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:15:10 +0000 Subject: [PATCH 028/151] fix(appkit-ui): update the old bar stacking test The options suite still asserted that vertical bars ignore stacked, the bug C8 fixed. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../appkit-ui/src/react/charts/__tests__/options.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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 8eab208ed..d0b503bb3 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -194,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] }, @@ -212,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"); }); }); From 15fac8caf4297169c19107d98ba1179c69846f60 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:15:44 +0000 Subject: [PATCH 029/151] fix(appkit-ui): truncate category labels to the width they have Labels were cut at a fixed length whatever the space (10 characters on a vertical x axis, 15 on horizontal bars, 10 and 12 on heatmaps), so twelve product lines all read "Consumer E..." and with five categories only three labels were drawn. BaseChart now measures its width with a ResizeObserver (rounded to 10 px). With a width, vertical category labels are all drawn and truncated with an ellipsis to their slot, rotating when slots get narrow; horizontal-bar and heatmap row labels get 30% of the width (60 to 220 px). Tooltips still show the full label. Without a measured width (server render, no ResizeObserver) the old character cut stays. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 68 ++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 21 ++++- .../appkit-ui/src/react/charts/options.ts | 79 +++++++++++++++---- 3 files changed, 151 insertions(+), 17 deletions(-) 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 index 79780dbb9..a028605d0 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -61,3 +61,71 @@ describe("horizontal bar row order (C13)", () => { expect(option.yAxis.inverse).toBeUndefined(); }); }); + +describe("category labels sized by width (C14)", () => { + 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...", + ); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index ab3fd5417..597963522 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -26,7 +26,7 @@ import { import * as echarts from "echarts/core"; import { LegacyGridContainLabel } from "echarts/features"; import { CanvasRenderer } from "echarts/renderers"; -import { useCallback, useEffect, useMemo, useRef } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { chartSizeStyle } from "./constants"; import { @@ -301,6 +301,12 @@ export function BaseChart({ // Store ECharts instance directly to avoid stale ref issues on unmount const echartsInstanceRef = useRef(null); + // 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 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) => { @@ -312,9 +318,20 @@ 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; + if (width > 0) setChartWidth(Math.round(width / 10) * 10); + }); + observer.observe(node.ele); + resizeObserverRef.current = observer; + } } else { // Component unmounting - dispose the stored instance if ( @@ -410,6 +427,7 @@ export function BaseChart({ xIsTime: detectedChartType === "timeseries", xDateOnly, v3, + chartWidth, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -501,6 +519,7 @@ export function BaseChart({ selected, interactive, v3, + chartWidth, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 2bc7831fc..3ca974f04 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -34,6 +34,8 @@ export interface OptionBuilderContext { xDateOnly?: boolean; /** Build with the `defaults="v3"` defaults. */ v3?: boolean; + /** Measured chart width in px, when known. Sizes axis labels. */ + chartWidth?: number; } export interface CartesianContext extends OptionBuilderContext { @@ -93,6 +95,48 @@ function mergeAxisLabel( }; } +/** 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; +/** 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 { + interval: slot >= 14 ? 0 : "auto", + rotate: 45, + width: ROTATED_LABEL_WIDTH, + overflow: "truncate", + }; +} + +/** 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))); +} + function legendTextStyle(ui: ChartUITokens) { return { textStyle: { color: ui.axisTitle } }; } @@ -293,12 +337,18 @@ export function buildHorizontalBarOption( // largest first. ...(ctx.v3 ? { inverse: true } : {}), ...mergeAxisLabel(ui, { - width: 100, + width: categoryYLabelWidth(ctx), overflow: "truncate", - formatter: ctx.xIsTime - ? (value: string) => - formatTimeLabel(Number(value), ctx.xDateOnly === true) - : (value: string) => truncateLabel(String(value)), + // 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)) }), }), // Dates on a category axis: format the tooltip header the same way. ...(ctx.xIsTime @@ -377,18 +427,18 @@ export function buildHeatmapOption( 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, @@ -514,10 +564,7 @@ export function buildCartesianOption( ui, isScatter || isValueX || isTimeSeries ? { show: true } - : { - rotate: ctx.xData.length > 10 ? 45 : 0, - formatter: (v: string) => truncateLabel(String(v), 10), - }, + : categoryXAxisLabel(ctx, ctx.xData.length, 10), ), }, yAxis: { From 2a897253695a967d981be39037764b79e3914045 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:16:27 +0000 Subject: [PATCH 030/151] fix(appkit-ui): leave axis names off under v3 Axis names sat at the end of the axis and were clipped ("Categ", "Quart"), the y name was cut at 160 px, and a title overlapped it. With defaults="v3" bar, line and area charts draw no axis names (the card title carries them); scatter keeps both names, centred below and beside the axes. Without v3 nothing changes. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 44 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 31 ++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) 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 index a028605d0..b2060683a 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -129,3 +129,47 @@ describe("category labels sized by width (C14)", () => { ); }); }); + +describe("axis names (C15)", () => { + 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" }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 3ca974f04..81050ea54 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -510,6 +510,28 @@ function scatterPoints( return points; } +/** + * 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 : 48, + }; +} + export function buildCartesianOption( ctx: CartesianContext, ): Record { @@ -559,7 +581,7 @@ export function buildCartesianOption( }, } : {}), - name: ctx.xField ? formatLabel(ctx.xField) : undefined, + ...axisName(ctx, isScatter, "x", ctx.xField), ...mergeAxisLabel( ui, isScatter || isValueX || isTimeSeries @@ -569,7 +591,12 @@ export function buildCartesianOption( }, yAxis: { type: "value", - name: ctx.yFields.length === 1 ? formatLabel(ctx.yFields[0]) : undefined, + ...axisName( + ctx, + isScatter, + "y", + ctx.yFields.length === 1 ? ctx.yFields[0] : undefined, + ), ...mergeAxisLabel(ui, valueAxisLabel(ctx)), }, series: ctx.yFields.map((key, idx) => ({ From 7b97b619376afe3e2331bad47438ed0a6bd602c1 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:16:55 +0000 Subject: [PATCH 031/151] fix(appkit-ui): reserve label space in the horizontal bar grid The horizontal bar grid was fixed at left 20% and bottom 5% with no room reserved for labels, so long category labels and the value ticks at the bottom edge were clipped. It now uses pixel margins with containLabel, so ECharts makes room for the labels. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 22 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 11 ++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) 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 index b2060683a..44ca28c71 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -173,3 +173,25 @@ describe("axis names (C15)", () => { expect(option.yAxis).toMatchObject({ name: "A", nameLocation: "middle" }); }); }); + +describe("horizontal bar grid (C16)", () => { + 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, + }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 81050ea54..406defea2 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -323,11 +323,14 @@ export function buildHorizontalBarOption( ctx.showLegend && hasMultipleSeries ? { top: "bottom", ...legendTextStyle(ui) } : undefined, + // 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: 24, + top: ctx.title ? 40 : 12, + bottom: ctx.showLegend && hasMultipleSeries ? 40 : 8, + containLabel: true, }, xAxis: { type: "value", ...mergeAxisLabel(ui, valueAxisLabel(ctx)) }, yAxis: { From c87ee8b7ce712a42cff71ea4c18d459cbc8b6a82 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:17:34 +0000 Subject: [PATCH 032/151] fix(appkit-ui): draw straight lines by default under v3 smooth defaulted to true, so a single spike was drawn as a bell three weeks wide. With defaults="v3", smooth defaults to false; an explicit smooth still wins. Without v3 the default stays true. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 29 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 7 +++-- packages/appkit-ui/src/react/charts/types.ts | 4 +-- 3 files changed, 36 insertions(+), 4 deletions(-) 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 index 83f278d81..c6ab5cf98 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -55,3 +55,32 @@ describe("chart-specific props (X8)", () => { ).toBe(true); }); }); + +describe("smooth default (C24)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 597963522..a92bb5ca2 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -179,7 +179,7 @@ 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; @@ -259,7 +259,7 @@ export function BaseChart({ colorPalette, colors: customColors, showSymbol = false, - smooth = true, + smooth: smoothProp, connectNulls = false, stacked = false, symbolSize = 8, @@ -278,6 +278,9 @@ export function BaseChart({ defaults, }: BaseChartProps) { const v3 = defaults === "v3"; + // 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). diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 19001f4f9..7a77fda16 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -289,7 +289,7 @@ export interface LineChartSpecificProps { symbolSize?: number; /** Show data point symbols @default false */ showSymbol?: boolean; - /** Smooth line curves @default true */ + /** Smooth line curves. @default true (false with `defaults="v3"`) */ smooth?: boolean; /** * Draw the line across missing values instead of leaving a gap. Only applies @@ -304,7 +304,7 @@ export interface AreaChartSpecificProps { symbolSize?: number; /** Show data point symbols @default false */ showSymbol?: boolean; - /** Smooth line curves @default true */ + /** Smooth line curves. @default true (false with `defaults="v3"`) */ smooth?: boolean; /** * Draw the line across missing values instead of leaving a gap. Only applies From 2e03abd3a5652a0179d5e0f7e69399ce83d073a6 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:19:01 +0000 Subject: [PATCH 033/151] fix(appkit-ui): compact ticks and full-value tooltips under v3 There was no default number format: ticks read "18,000,000" and tooltips "15,234,567.891". With defaults="v3" and no valueFormatter, value-axis ticks and heatmap scale labels use compact numbers ("18M") and tooltips show the full value with grouping and at most two decimals. A valueFormatter still formats both. Option builders gain axisValueFormatter for ticks. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 47 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 7 ++- .../appkit-ui/src/react/charts/options.ts | 9 ++-- packages/appkit-ui/src/react/charts/utils.ts | 23 +++++++++ 4 files changed, 81 insertions(+), 5 deletions(-) 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 index c6ab5cf98..aa9b5fcd8 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -84,3 +84,50 @@ describe("smooth default (C24)", () => { expect(option?.series[0].smooth).toBe(true); }); }); + +describe("default number format (C22)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index a92bb5ca2..875bfae81 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -57,7 +57,7 @@ import type { Orientation, XAxisType, } from "./types"; -import { mapToDatum } from "./utils"; +import { formatCompactNumber, formatFullNumber, mapToDatum } from "./utils"; // ============================================================================ // ECharts Registration (modular imports for tree-shaking) @@ -426,7 +426,10 @@ export function BaseChart({ showLegend, xField, ui, - valueFormatter, + // v3 without a formatter: compact ticks, full values in tooltips. + valueFormatter: valueFormatter ?? (v3 ? formatFullNumber : undefined), + axisValueFormatter: + valueFormatter ?? (v3 ? formatCompactNumber : undefined), xIsTime: detectedChartType === "timeseries", xDateOnly, v3, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 406defea2..64f60853d 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -28,6 +28,8 @@ export interface OptionBuilderContext { xField?: string; ui?: ChartUITokens; valueFormatter?: ChartValueFormatter; + /** Formats value-axis ticks and color-scale labels. Falls back to `valueFormatter`. */ + axisValueFormatter?: ChartValueFormatter; /** x holds timestamps drawn on a category axis (horizontal bars). */ xIsTime?: boolean; /** x holds DATE values (no time of day). */ @@ -165,7 +167,7 @@ function tooltipValueFormatter(formatter: ChartValueFormatter, field: string) { function valueAxisLabel(ctx: OptionBuilderContext) { const field = ctx.yFields[0]; - const formatter = ctx.valueFormatter; + const formatter = ctx.axisValueFormatter ?? ctx.valueFormatter; return formatter && field ? { formatter: (value: string | number) => formatter(value, field) } : {}; @@ -404,6 +406,7 @@ 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); return { @@ -452,8 +455,8 @@ export function buildHeatmapOption( top: "center", textStyle: { color: ui.axisTitle }, 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 diff --git a/packages/appkit-ui/src/react/charts/utils.ts b/packages/appkit-ui/src/react/charts/utils.ts index 1c4bab2db..44c090084 100644 --- a/packages/appkit-ui/src/react/charts/utils.ts +++ b/packages/appkit-ui/src/react/charts/utils.ts @@ -450,3 +450,26 @@ export function sortTimeSeriesAscending( return { xData: sortedXData, yDataMap: sortedYDataMap }; } + +const compactNumber = new Intl.NumberFormat(undefined, { + notation: "compact", + maximumFractionDigits: 1, +}); +const fullNumber = new Intl.NumberFormat(undefined, { + maximumFractionDigits: 2, +}); + +function formatNumberWith(format: Intl.NumberFormat) { + return (value: string | number): string => { + const n = typeof value === "number" ? value : Number(value); + return value !== "" && Number.isFinite(n) + ? format.format(n) + : String(value); + }; +} + +/** `defaults="v3"` axis ticks: compact numbers ("18M", "2.5K"). */ +export const formatCompactNumber = formatNumberWith(compactNumber); + +/** `defaults="v3"` tooltips: the full value with grouping ("15,234,567.89"). */ +export const formatFullNumber = formatNumberWith(fullNumber); From cea92d827c3dc08a138176a8aa183bd7f8d43e0c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:20:42 +0000 Subject: [PATCH 034/151] fix(appkit-ui): resolve var() theme tokens passed in colors colors could not take theme tokens: var(--chart-cat-1) drew grey and dropped the legend marker, because ECharts draws on a canvas, and lint rules forbid color literals, so there was no allowed way to pin a series color. Custom colors written as var(--name) or var(--name, fallback) are now resolved against the root element computed style before they reach ECharts, and again when the theme changes. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/theme.test.ts | 31 +++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 6 ++- packages/appkit-ui/src/react/charts/theme.ts | 52 +++++++++++++++++++ packages/appkit-ui/src/react/charts/types.ts | 11 ++-- 4 files changed, 94 insertions(+), 6 deletions(-) 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..13e718dd7 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 (C23)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 875bfae81..c9426b716 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -45,7 +45,7 @@ import { mergeChartOptions, type OptionBuilderContext, } from "./options"; -import { useChartUITokens, useThemeColors } from "./theme"; +import { useChartUITokens, useResolvedColors, useThemeColors } from "./theme"; import type { ChartBaseProps, ChartClickDatum, @@ -288,7 +288,9 @@ export function BaseChart({ // Determine the appropriate color palette based on chart type const resolvedPalette = 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; const ui = useChartUITokens(); diff --git a/packages/appkit-ui/src/react/charts/theme.ts b/packages/appkit-ui/src/react/charts/theme.ts index 1572c434c..a7d6ade40 100644 --- a/packages/appkit-ui/src/react/charts/theme.ts +++ b/packages/appkit-ui/src/react/charts/theme.ts @@ -231,6 +231,58 @@ export function useChartUITokens(): ChartUITokens { return tokens; } +const CSS_VAR_PATTERN = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+?)\s*)?\)$/; + +/** + * Resolves `var(--name)` and `var(--name, fallback)` colors against the root + * element's computed style. ECharts draws on a canvas and can't resolve + * `var()`, so an unresolved token draws grey. Other colors pass through. + */ +function resolveColors(colors: string[]): string[] { + if (typeof window === "undefined") return colors; + if (!colors.some((color) => CSS_VAR_PATTERN.test(color.trim()))) { + return colors; + } + const styles = getComputedStyle(document.documentElement); + return colors.map((color) => { + const match = CSS_VAR_PATTERN.exec(color.trim()); + if (!match) return color; + const value = styles.getPropertyValue(match[1]).trim(); + return value || match[2] || color; + }); +} + +/** + * Hook that resolves theme tokens in custom `colors` (`var(--chart-cat-1)`) + * to concrete colors, again whenever the theme changes. + */ +export function useResolvedColors( + colors: string[] | undefined, +): string[] | undefined { + const key = colors?.join("|"); + const [resolved, setResolved] = useState(() => + colors ? resolveColors(colors) : undefined, + ); + const colorsRef = useRef(colors); + colorsRef.current = colors; + + // Re-resolve when the colors change by content, not array identity. + useEffect(() => { + setResolved( + colorsRef.current ? resolveColors(colorsRef.current) : undefined, + ); + }, [key]); + + const update = useCallback(() => { + setResolved( + colorsRef.current ? resolveColors(colorsRef.current) : undefined, + ); + }, []); + useThemeChangeEffect(update); + + return resolved; +} + /** * Hook to get all three color palettes at once. * Useful when a component needs access to multiple palette types. diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 7a77fda16..6bfcc2df9 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -106,10 +106,13 @@ export interface ChartBaseProps { */ colorPalette?: ChartColorPalette; /** - * 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. + * 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. */ colors?: string[]; /** From 7faf3a785802986bbc9f727194613c61d93bf672 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:21:42 +0000 Subject: [PATCH 035/151] fix(appkit-ui): draw bars over dates on a category axis of formatted dates Bars on a time axis stuck out of the plot at both ends, the first tick labels collided ("2026" over "2") and the last label was missing. Vertical bars over dates now use a category axis holding the dates, labelled and tooltipped with the same date formatting as horizontal bars, so every bar has a band and a label. Lines and areas keep the time axis. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 40 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 35 ++++++++++++---- 2 files changed, 68 insertions(+), 7 deletions(-) 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 index 44ca28c71..efd983a64 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -195,3 +195,43 @@ describe("horizontal bar grid (C16)", () => { }); }); }); + +describe("bars over dates (C25)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 64f60853d..48576f9e0 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -556,6 +556,13 @@ export function buildCartesianOption( const seriesType = chartType === "area" ? "line" : chartType; const isScatter = chartType === "scatter"; const isLineLike = chartType === "line" || chartType === "area"; + // 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; + const dateLabel = (value: string | number) => + formatTimeLabel(Number(value), ctx.xDateOnly === true); return { ...buildBaseOption(ctx), @@ -572,12 +579,11 @@ export function buildCartesianOption( containLabel: true, }, xAxis: { - type: - isScatter || isValueX ? "value" : isTimeSeries ? "time" : "category", - data: isScatter || isValueX || isTimeSeries ? undefined : ctx.xData, + type: isScatter || isValueX ? "value" : isTimeAxis ? "time" : "category", + 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.) - ...(isTimeSeries && ctx.xDateOnly + ...(isTimeAxis && ctx.xDateOnly ? { axisPointer: { label: { @@ -587,12 +593,27 @@ export function buildCartesianOption( }, } : {}), + ...(isTimeBar + ? { + axisPointer: { + label: { + formatter: (params: { value: string | number }) => + dateLabel(params.value), + }, + }, + } + : {}), ...axisName(ctx, isScatter, "x", ctx.xField), ...mergeAxisLabel( ui, - isScatter || isValueX || isTimeSeries + isScatter || isValueX || isTimeAxis ? { show: true } - : categoryXAxisLabel(ctx, ctx.xData.length, 10), + : isTimeBar + ? { + ...categoryXAxisLabel(ctx, ctx.xData.length, 10), + formatter: dateLabel, + } + : categoryXAxisLabel(ctx, ctx.xData.length, 10), ), }, yAxis: { @@ -612,7 +633,7 @@ export function buildCartesianOption( ? scatterPoints(ctx.xData, ctx.yDataMap[key]) : isValueX ? ctx.xData.map((x, i) => [x, ctx.yDataMap[key][i]]) - : isTimeSeries + : isTimeAxis ? createTimeSeriesData(ctx.xData, ctx.yDataMap[key]) : ctx.yDataMap[key], smooth: isLineLike ? smooth : undefined, From 3d9ef3136661863900c4e57d5d4632f4de5814f3 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:22:53 +0000 Subject: [PATCH 036/151] feat(appkit-ui): keep the chart box for states and add loading/error in data mode Empty and error states ignored height (a 300 px chart collapsed to 86 px when the data was empty), and data mode had no loading or error prop, so data={rows ?? []} showed "No data available" while loading. Empty, error and render-failure states now sit in a box with the chart height and className. Data mode charts accept loading (shows the skeleton) and error (string or Error). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/sizing.test.tsx | 41 +++++++++ .../src/react/charts/create-chart.tsx | 8 ++ packages/appkit-ui/src/react/charts/types.ts | 9 ++ .../appkit-ui/src/react/charts/wrapper.tsx | 92 ++++++++++++++++++- 4 files changed, 145 insertions(+), 5 deletions(-) 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 47740689f..64079ea52 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/sizing.test.tsx @@ -87,3 +87,44 @@ describe("className heights and v3 default height (C11)", () => { expect(chartSizeStyle(208, { defaults: "v3" })).toEqual({ height: 208 }); }); }); + +describe("states keep the chart box (C26)", () => { + 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/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index b5fec7b0b..d046fe26a 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -51,6 +51,8 @@ const SHARED_PROPS = [ "format", "transformer", "data", + "loading", + "error", ]; const PIE_PROPS = allKeys()([ @@ -142,6 +144,8 @@ export function createChart( transformer, // Data props data, + loading, + error, // Common props height, className, @@ -156,6 +160,8 @@ export function createChart( format?: string; transformer?: unknown; data?: unknown; + loading?: boolean; + error?: string | Error | null; height?: number; className?: string; ariaLabel?: string; @@ -169,6 +175,8 @@ export function createChart( // runtime they're the same plain objects the chart reads. { data: data as ChartData, + loading, + error, height, className, ariaLabel, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 6bfcc2df9..dd762bb34 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -244,6 +244,8 @@ export interface QueryProps extends ChartBaseProps { transformer?: ChartTransformer; // Discriminator: cannot use direct data with query data?: never; + loading?: never; + error?: never; } // ============================================================================ @@ -254,6 +256,13 @@ export interface QueryProps extends ChartBaseProps { export interface DataProps extends ChartBaseProps { /** Arrow Table or an array of row objects (interfaces and `as const` arrays too). */ data: ChartDataInput; + /** + * 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}`). + */ + loading?: boolean; + /** Show this error instead of the chart, in the chart's box. */ + error?: string | Error | null; // Discriminator: cannot use query props with direct data queryKey?: never; diff --git a/packages/appkit-ui/src/react/charts/wrapper.tsx b/packages/appkit-ui/src/react/charts/wrapper.tsx index 329bbcc92..20ead6cf8 100644 --- a/packages/appkit-ui/src/react/charts/wrapper.tsx +++ b/packages/appkit-ui/src/react/charts/wrapper.tsx @@ -32,6 +32,38 @@ function isWarehouseWaiting( return true; } +/** + * Holds a loading, empty or error state in the chart's own box, so the card + * doesn't collapse (a 300 px chart used to shrink to 86 px when empty). + */ +function StateBox({ + className, + style, + testId, + children, +}: { + className?: string; + style: ReturnType; + testId?: string; + children: ReactNode; +}) { + return ( +
+ {children} +
+ ); +} + +function errorMessage(error: string | Error): string { + return typeof error === "string" ? error : error.message; +} + // ============================================================================ // Props Types // ============================================================================ @@ -47,11 +79,17 @@ interface ChartWrapperQueryProps { transformer?: ChartTransformer; /** Direct data - not used in query mode */ data?: never; + loading?: never; + error?: never; } interface ChartWrapperDataProps { /** Direct data (Arrow Table or JSON array) */ data: ChartData; + /** Show the loading state instead of the chart (data mode). */ + loading?: boolean; + /** Show this error instead of the chart (data mode). */ + error?: string | Error | null; /** Not used in data mode */ queryKey?: never; parameters?: never; @@ -115,12 +153,28 @@ function QueryModeContent({
); } - if (error) return ; - if (isEmpty || !data) return ; + if (error) { + return ( + + + + ); + } + if (isEmpty || !data) { + return ( + + + + ); + } return ( } + fallback={ + + + + } >
; + if (loading) { + return ( +
+ +
+ ); + } + if (error) { + return ( + + + + ); + } + if (isEmpty) { + return ( + + + + ); + } return ( } + fallback={ + + + + } >
Date: Tue, 1 Dec 2026 21:23:43 +0000 Subject: [PATCH 037/151] fix(appkit-ui): give charts an accessible name by default The chart box has role="img" and had no accessible name unless ariaLabel was passed. Without ariaLabel the name is now built from the chart type and the title ("Area chart: Revenue") or the fields ("Line chart of revenue by month"). An explicit ariaLabel still wins. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 27 +++++++++++ .../src/react/charts/create-chart.tsx | 48 ++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) 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 index aa9b5fcd8..43408a77c 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -131,3 +131,30 @@ describe("default number format (C22)", () => { expect(option?.yAxis[0].axisLabel.formatter?.(5)).toBe("USD 5"); }); }); + +describe("default accessible name (C27)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index d046fe26a..a058a17b3 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -13,6 +13,7 @@ import type { ScatterChartSpecificProps, UnifiedChartProps, } from "./types"; +import { formatLabel } from "./utils"; import { ChartWrapper } from "./wrapper"; /** @@ -89,6 +90,40 @@ const CHART_PROPS: Record = { ]), }; +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(); /** @@ -169,6 +204,15 @@ export function createChart( defaults?: ChartDefaults; }; + const label = + ariaLabel ?? + defaultAriaLabel( + chartType, + chartProps.title, + chartProps.xKey, + chartProps.yKey, + ); + const wrapperProps = data !== undefined ? // ChartDataInput also admits interface-typed and readonly rows; at @@ -179,7 +223,7 @@ export function createChart( error, height, className, - ariaLabel, + ariaLabel: label, testId, defaults, } @@ -190,7 +234,7 @@ export function createChart( transformer, height, className, - ariaLabel, + ariaLabel: label, testId: testId ?? `${chartType}-chart-${queryKey}`, defaults, }; From eac3bb0289908658a2f5a78e2ad7e17f887eaf2a Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:25:04 +0000 Subject: [PATCH 038/151] fix(appkit-ui): skip dimming when selected matches nothing and match date bars selected with a name that is not in the data dimmed every mark to 30% and highlighted none, which is the state after a filter removes the selected row. Now, when no bar category or pie slice matches, the chart is left as is. Bars over dates (category axis of timestamps since C25) now match a date selection such as "2026-01-02". Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 43 +++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 53 ++++++++++++++++--- 2 files changed, 89 insertions(+), 7 deletions(-) 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 index efd983a64..b241876db 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "vitest"; import { + applySelectionEmphasis, buildCartesianOption, buildHorizontalBarOption, type CartesianContext, @@ -235,3 +236,45 @@ describe("bars over dates (C25)", () => { expect(option.xAxis.type).toBe("time"); }); }); + +describe("selection that matches nothing, and date bars (X4)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 48576f9e0..eee753bac 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -11,6 +11,7 @@ import { formatLabel, formatLocalDate, formatTimeLabel, + toChronologicalValue, truncateLabel, } from "./utils"; @@ -867,6 +868,43 @@ function emphasizeSeries( return { ...s, data }; } +/** Whether any pie slice or bar category of the option is in `selected`. */ +function selectionMatches( + series: unknown[], + selected: Set, + categoryNames: (string | number)[] | null, +): boolean { + if (categoryNames?.some((name) => selected.has(String(name)))) { + return series.some( + (s) => isPlainObject(s) && s.type === "bar" && Array.isArray(s.data), + ); + } + return series.some( + (s) => + isPlainObject(s) && + s.type === "pie" && + Array.isArray(s.data) && + s.data.some( + (d) => isPlainObject(d) && "name" in d && selected.has(String(d.name)), + ), + ); +} + +/** + * Adds the timestamp form of date selections ("2026-01-01"), so `selected` + * matches bars whose category axis holds dates. + */ +function withDateForms(selected: Set): Set { + const out = new Set(selected); + for (const name of selected) { + const timestamp = toChronologicalValue(name); + if (timestamp !== null) { + out.add(String(timestamp)); + } + } + return out; +} + /** * Pure, declarative selection-emphasis transform for a built ECharts `option`. * @@ -898,15 +936,16 @@ export function applySelectionEmphasis( const dimmedOpacity = opts.dimmedOpacity ?? DIMMED_OPACITY; const selectedOpacity = opts.selectedOpacity ?? SELECTED_OPACITY; const categoryNames = categoryNamesFromAxes(opt); + const names = withDateForms(selectedSet); + + // A selection that matches nothing (e.g. after a filter removed the row) + // leaves the chart as is instead of dimming every mark. + if (!selectionMatches(opt.series as unknown[], names, categoryNames)) { + return option; + } const series = (opt.series as unknown[]).map((s) => - emphasizeSeries( - s, - selectedSet, - dimmedOpacity, - selectedOpacity, - categoryNames, - ), + emphasizeSeries(s, names, dimmedOpacity, selectedOpacity, categoryNames), ); return { ...opt, series } as T; From 3097ae6a4a62a917212dbf02c9f859d6c81fe862 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:25:51 +0000 Subject: [PATCH 039/151] fix(appkit-ui): draw single data points on line, area and bar charts One data point drew nothing on a line or area chart, because symbols are off by default, so a KPI sparkline on its first day was an empty box. On a time axis a single date spanned two days of hourly ticks, and a single bar filled about 70% of the plot. Now a line or area series with at most one value shows its symbol, a time axis with one x value is padded by a day (an hour for timestamps), DATE time axes never tick below a day, and a lone bar is at most 80 px wide. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 43 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 35 ++++++++++++++- 2 files changed, 77 insertions(+), 1 deletion(-) 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 index b241876db..31d8cd94b 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -278,3 +278,46 @@ describe("selection that matches nothing, and date bars (X4)", () => { expect(applySelectionEmphasis(pie, "Z")).toBe(pie); }); }); + +describe("a single data point (X5)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index eee753bac..d8d9bc746 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -517,6 +517,25 @@ function scatterPoints( return points; } +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 }; +} + /** * 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 @@ -584,6 +603,13 @@ export function buildCartesianOption( 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: { @@ -639,7 +665,14 @@ export function buildCartesianOption( : ctx.yDataMap[key], smooth: isLineLike ? smooth : undefined, connectNulls: isLineLike && ctx.connectNulls ? true : undefined, - showSymbol: isLineLike ? showSymbol : undefined, + // A series with one point has no line to draw: show its symbol. + showSymbol: isLineLike + ? showSymbol || countValues(ctx.yDataMap[key]) <= 1 + : undefined, + // A single bar would fill most of the plot. + ...(chartType === "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. From f98f758e5e31245f4c9059b8150114b759b1e365 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:27:15 +0000 Subject: [PATCH 040/151] fix(appkit-ui): fit scatter axes to the data and show both fields in the tooltip Value axes always started at 0, so a scatter of x 5,000 to 6,000 and y 97 to 99.5 sat in one corner, and the scatter tooltip showed only y. Scatter x and y axes now scale to the data, and the tooltip lists both fields by name with their (formatted) values, plus the series name when there are several. Point labels, size and color by a column are left to the scatter P2 ticket. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 37 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 37 ++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-) 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 index 31d8cd94b..500aea4ac 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -321,3 +321,40 @@ describe("a single data point (X5)", () => { expect(option.series[0].barMaxWidth).toBe(80); }); }); + +describe("scatter axes and tooltip (C19)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index d8d9bc746..73acff7b5 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -504,6 +504,33 @@ function toFiniteNumber(value: unknown): number | 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) { + const xField = ctx.xField ?? "x"; + const format = (value: unknown, field: string) => { + 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("
"); + }; +} + function scatterPoints( xData: (string | number)[], yData: ChartValue[], @@ -586,7 +613,12 @@ export function buildCartesianOption( 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) } : {}), + }, legend: ctx.showLegend && hasMultipleSeries ? { top: "bottom", ...legendTextStyle(ui) } @@ -600,6 +632,7 @@ export function buildCartesianOption( }, xAxis: { type: isScatter || isValueX ? "value" : isTimeAxis ? "time" : "category", + ...(isScatter ? { 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.) @@ -645,6 +678,8 @@ export function buildCartesianOption( }, yAxis: { type: "value", + // Scatter axes fit the data instead of starting at 0. + ...(isScatter ? { scale: true } : {}), ...axisName( ctx, isScatter, From 29087c9251ff1757f4d77c360d393bbc90105d7f Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:28:37 +0000 Subject: [PATCH 041/151] fix(appkit-ui): show an error when a scatter x holds text A string x drew nothing, because the scatter x axis is always numeric, while the legend showed and nothing was logged. When no x value is a number, the scatter now renders an error state naming the key and an example value, pointing at BarChart for categories, and logs console.error. The registration test now gives the scatter a numeric x. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 55 ++++++++++++++++++- packages/appkit-ui/src/react/charts/base.tsx | 41 ++++++++++++-- 2 files changed, 89 insertions(+), 7 deletions(-) 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 02429e15e..356e7cb7c 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( , @@ -513,3 +521,46 @@ describe("orientation on line and area (C9)", () => { }, ); }); + +describe("scatter with text x (SCAT-02)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index c9426b716..a774e0f26 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -117,6 +117,28 @@ 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 !== ""); + 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.`; +} + // ============================================================================ // Bar Orientation // ============================================================================ @@ -354,9 +376,6 @@ export function BaseChart({ () => unknownKeysMessage(data, { xKey, yKey, yAxisKey, seriesKey }), [data, xKey, yKey, yAxisKey, seriesKey], ); - useEffect(() => { - if (keyError) console.error(`[appkit-ui] ${chartType} chart: ${keyError}`); - }, [keyError, chartType]); // Memoize data normalization const normalized = useMemo( @@ -380,6 +399,18 @@ export function BaseChart({ [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3, seriesKey], ); + // Data a chart can't draw is reported instead of drawing an empty plot. + const chartError = useMemo( + () => + keyError ?? (chartType === "scatter" ? scatterXError(normalized) : null), + [keyError, chartType, normalized], + ); + useEffect(() => { + if (chartError) { + console.error(`[appkit-ui] ${chartType} chart: ${chartError}`); + } + }, [chartError, 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; @@ -571,14 +602,14 @@ export function BaseChart({ [interactive], ); - if (keyError) { + if (chartError) { return (
- {keyError} + {chartError}
); } From 1905cd79dcb680049df533025db7004d671dbeb9 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:29:30 +0000 Subject: [PATCH 042/151] fix(appkit-ui): plot scatter dates on a time axis DATE strings on a scatter x were plotted as epoch milliseconds on a value axis, with overlapping tick labels such as "300,000,000,000". When the x values are dates, the scatter x axis is now a time axis and the tooltip shows the date. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 26 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 21 +++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) 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 356e7cb7c..8dcc3c098 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -564,3 +564,29 @@ describe("scatter with text x (SCAT-02)", () => { expect(queryByRole("alert")).toBeNull(); }); }); + +describe("scatter over dates (SCAT-05)", () => { + 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()); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 73acff7b5..a59434e34 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -505,9 +505,12 @@ function toFiniteNumber(value: unknown): number | null { * 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) { +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); @@ -602,12 +605,14 @@ export function buildCartesianOption( const hasMultipleSeries = ctx.yFields.length > 1; const seriesType = chartType === "area" ? "line" : chartType; const isScatter = chartType === "scatter"; + // A scatter over dates plots them on a time axis, not as epoch numbers. + const isTimeScatter = isScatter && isTimeSeries; const isLineLike = chartType === "line" || chartType === "area"; // 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; + const isTimeAxis = isTimeSeries && !isTimeBar && !isScatter; const dateLabel = (value: string | number) => formatTimeLabel(Number(value), ctx.xDateOnly === true); @@ -617,7 +622,7 @@ export function buildCartesianOption( ...tooltipTokens(ui), trigger: isScatter ? "item" : "axis", // Scatter: both measures, named, not just y. - ...(isScatter ? { formatter: scatterTooltip(ctx) } : {}), + ...(isScatter ? { formatter: scatterTooltip(ctx, isTimeScatter) } : {}), }, legend: ctx.showLegend && hasMultipleSeries @@ -631,8 +636,14 @@ export function buildCartesianOption( containLabel: true, }, xAxis: { - type: isScatter || isValueX ? "value" : isTimeAxis ? "time" : "category", - ...(isScatter ? { scale: true } : {}), + 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.) From 48d0b416c35228d4fecd31db736694a042190e44 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:30:14 +0000 Subject: [PATCH 043/151] fix(appkit-ui): give scatter points an opacity that falls with the count Scatter points had no opacity, so twenty identical points looked like one and 10,000 points were a solid block. Points now have opacity 0.8 up to 50 points, 0.6 up to 500, 0.35 up to 5,000 and 0.2 beyond, so overlaps show as denser color. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 20 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 16 ++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) 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 index 500aea4ac..a09aa235d 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -358,3 +358,23 @@ describe("scatter axes and tooltip (C19)", () => { expect(option.yAxis.scale).toBeUndefined(); }); }); + +describe("scatter point opacity (SCAT-08)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index a59434e34..c15f5ff9e 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -534,6 +534,14 @@ function scatterTooltip(ctx: OptionBuilderContext, xIsTime = false) { }; } +/** 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; +} + function scatterPoints( xData: (string | number)[], yData: ChartValue[], @@ -720,6 +728,7 @@ export function buildCartesianOption( ? { 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. symbolSize: isScatter || isLineLike ? symbolSize : undefined, @@ -732,7 +741,12 @@ export function buildCartesianOption( ? "total" : undefined, itemStyle: - chartType === "bar" ? { borderRadius: [4, 4, 0, 0] } : undefined, + chartType === "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 ? { From adec8d1095dd0989a5003a99aea0985f5e222f79 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:31:54 +0000 Subject: [PATCH 044/151] feat(appkit-ui): add referenceLines for target and reference lines There was no way to draw a target or reference line: markLine was not registered and series could not be extended. Bar, line, area and scatter charts take referenceLines={[{ value, label? }]}, drawn as a dashed, labelled markLine across the plot at that value of the value axis (x on horizontal bars). MarkLineComponent is now registered; the label defaults to the formatted value. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 34 ++++++++ packages/appkit-ui/src/react/charts/base.tsx | 14 +++- .../src/react/charts/create-chart.tsx | 13 ++- packages/appkit-ui/src/react/charts/index.ts | 1 + .../appkit-ui/src/react/charts/options.ts | 83 +++++++++++++++---- packages/appkit-ui/src/react/charts/types.ts | 25 +++++- 6 files changed, 145 insertions(+), 25 deletions(-) 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 8dcc3c098..ab56a497f 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -590,3 +590,37 @@ describe("scatter over dates (SCAT-05)", () => { expect(option.series[0].data[0][0]).toBe(new Date(2026, 0, 1).getTime()); }); }); + +describe("reference lines (C31)", () => { + 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([]); + }, + ); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index a774e0f26..51f920d28 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -19,6 +19,7 @@ import { import { GridComponent, LegendComponent, + MarkLineComponent, TitleComponent, TooltipComponent, VisualMapComponent, @@ -52,6 +53,7 @@ import type { ChartColorPalette, ChartData, ChartDefaults, + ChartReferenceLine, ChartType, ChartValueFormatter, Orientation, @@ -67,8 +69,8 @@ import { formatCompactNumber, formatFullNumber, 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"`. // @@ -93,6 +95,7 @@ echarts.use([ LegendComponent, // `legend` GridComponent, // `grid` / `xAxis` / `yAxis` VisualMapComponent, // `visualMap` (heatmap color scale) + MarkLineComponent, // `markLine` (referenceLines) // Features LegacyGridContainLabel, // `grid.containLabel` (cartesian option builder) // Renderer (BaseChart always renders with `renderer: "canvas"`) @@ -227,7 +230,7 @@ export interface BaseChartProps { * 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`, `dataZoom`, * `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 @@ -257,6 +260,8 @@ export interface BaseChartProps { selected?: string | string[]; /** Opt into the v3 defaults. See {@link ChartDefaults}. */ defaults?: ChartDefaults; + /** Target or reference lines (bar, line, area, scatter). */ + referenceLines?: ChartReferenceLine[]; } // ============================================================================ @@ -298,6 +303,7 @@ export function BaseChart({ onDataClick, selected, defaults, + referenceLines, }: BaseChartProps) { const v3 = defaults === "v3"; // v3: straight lines. Smoothing invents values between points (a one-day @@ -467,6 +473,7 @@ export function BaseChart({ xDateOnly, v3, chartWidth, + referenceLines, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -559,6 +566,7 @@ export function BaseChart({ interactive, v3, chartWidth, + referenceLines, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index a058a17b3..ffb446a54 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -64,21 +64,30 @@ const PIE_PROPS = allKeys()([ /** Props each chart type reads, beyond the shared ones. */ const CHART_PROPS: Record = { - bar: allKeys()(["orientation", "stacked"]), + bar: allKeys()([ + "orientation", + "stacked", + "referenceLines", + ]), line: allKeys()([ + "referenceLines", "symbolSize", "showSymbol", "smooth", "connectNulls", ]), area: allKeys()([ + "referenceLines", "symbolSize", "showSymbol", "smooth", "connectNulls", "stacked", ]), - scatter: allKeys()(["symbolSize"]), + scatter: allKeys()([ + "symbolSize", + "referenceLines", + ]), pie: PIE_PROPS, donut: PIE_PROPS, radar: allKeys()(["showArea"]), diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts index c99fcdd2f..85718aa49 100644 --- a/packages/appkit-ui/src/react/charts/index.ts +++ b/packages/appkit-ui/src/react/charts/index.ts @@ -111,6 +111,7 @@ export type { ChartData, ChartDataInput, ChartDefaults, + ChartReferenceLine, ChartRow, ChartTransformer, ChartType, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index c15f5ff9e..3708d4404 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -1,5 +1,6 @@ import { FALLBACK_UI_TOKENS } from "./constants"; import type { + ChartReferenceLine, ChartType, ChartUITokens, ChartValue, @@ -39,6 +40,8 @@ export interface OptionBuilderContext { v3?: boolean; /** Measured chart width in px, when known. Sizes axis labels. */ chartWidth?: number; + /** Target or reference lines at values of the value axis. */ + referenceLines?: ChartReferenceLine[]; } export interface CartesianContext extends OptionBuilderContext { @@ -368,19 +371,23 @@ export function buildHorizontalBarOption( } : {}), }, - 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 - ? { - valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key), - } - : undefined, - })), + series: withReferenceLines( + 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 + ? { + valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key), + } + : undefined, + })), + ctx, + "xAxis", + ), }; } @@ -574,6 +581,46 @@ function singleDateRange( return { min: timestamp - pad, max: timestamp + pad }; } +/** + * 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] ?? ""; + const format = ctx.valueFormatter ?? ctx.axisValueFormatter; + 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: { + formatter: + line.label ?? + (format ? format(line.value, field) : String(line.value)), + }, + })), + }; +} + +/** 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 @@ -707,7 +754,11 @@ export function buildCartesianOption( ), ...mergeAxisLabel(ui, valueAxisLabel(ctx)), }, - series: ctx.yFields.map((key, idx) => ({ + series: withReferenceLines(cartesianSeries(), ctx, "yAxis"), + }; + + function cartesianSeries(): Record[] { + return ctx.yFields.map((key, idx) => ({ name: formatLabel(key), type: seriesType, data: isScatter @@ -753,8 +804,8 @@ export function buildCartesianOption( valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key), } : undefined, - })), - }; + })); + } } // ============================================================================ diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index dd762bb34..8776ff696 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -282,8 +282,25 @@ export type UnifiedChartProps = QueryProps | DataProps; // Chart-Specific Props // ============================================================================ +/** A horizontal (or, on a horizontal bar chart, vertical) target or reference line. */ +export interface ChartReferenceLine { + /** Value on the value axis where the line is drawn. */ + value: number; + /** Label at the end of the line. Defaults to the formatted value. */ + label?: string; +} + +/** Props of charts with a value axis (bar, line, area, scatter). */ +interface ReferenceLineProps { + /** + * Target or reference lines across the plot, at values of the value axis + * (`[{ value: 100, label: "Target" }]`). + */ + referenceLines?: ChartReferenceLine[]; +} + /** Props specific to bar charts */ -export interface BarChartSpecificProps { +export interface BarChartSpecificProps extends ReferenceLineProps { /** * Bar orientation. When unset, dates are vertical and category labels are * horizontal. With `defaults="v3"`: dates, numbers (such as years) and up @@ -296,7 +313,7 @@ export interface BarChartSpecificProps { } /** Props specific to line charts */ -export interface LineChartSpecificProps { +export interface LineChartSpecificProps extends ReferenceLineProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ @@ -311,7 +328,7 @@ export interface LineChartSpecificProps { } /** Props specific to area charts */ -export interface AreaChartSpecificProps { +export interface AreaChartSpecificProps extends ReferenceLineProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ @@ -328,7 +345,7 @@ export interface AreaChartSpecificProps { } /** Props specific to scatter charts */ -export interface ScatterChartSpecificProps { +export interface ScatterChartSpecificProps extends ReferenceLineProps { /** Symbol size @default 8 */ symbolSize?: number; } From dfbdf31f8077350880798d21bd6b0e8561302bd0 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:33:14 +0000 Subject: [PATCH 045/151] feat(appkit-ui): add a zoom prop for long series dataZoom was not registered: options with dataZoom logged one console error and drew no slider. Bar, line and area charts take zoom, which adds wheel/drag zoom inside the plot and a slider along the category or time axis (on the right edge for horizontal bars) and makes room for it in the grid. DataZoomComponent is now registered. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/base.test.tsx | 45 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 9 +++- .../src/react/charts/create-chart.tsx | 3 ++ .../appkit-ui/src/react/charts/options.ts | 40 +++++++++++++++-- packages/appkit-ui/src/react/charts/types.ts | 15 +++++-- 5 files changed, 105 insertions(+), 7 deletions(-) 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 ab56a497f..05064b912 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/base.test.tsx @@ -624,3 +624,48 @@ describe("reference lines (C31)", () => { }, ); }); + +describe("zoom (C32)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 51f920d28..8fe7e7f8d 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -17,6 +17,7 @@ import { ScatterChart, } from "echarts/charts"; import { + DataZoomComponent, GridComponent, LegendComponent, MarkLineComponent, @@ -96,6 +97,7 @@ echarts.use([ 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"`) @@ -230,7 +232,7 @@ export interface BaseChartProps { * Additional ECharts options to merge. * * Only the built-in feature set is registered by this package, so options - * referencing extra ECharts features (`toolbox`, `dataZoom`, + * 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 @@ -262,6 +264,8 @@ export interface BaseChartProps { defaults?: ChartDefaults; /** Target or reference lines (bar, line, area, scatter). */ referenceLines?: ChartReferenceLine[]; + /** Zoom along the category or time axis (bar, line, area). */ + zoom?: boolean; } // ============================================================================ @@ -304,6 +308,7 @@ export function BaseChart({ selected, defaults, referenceLines, + zoom = false, }: BaseChartProps) { const v3 = defaults === "v3"; // v3: straight lines. Smoothing invents values between points (a one-day @@ -474,6 +479,7 @@ export function BaseChart({ v3, chartWidth, referenceLines, + zoom, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -567,6 +573,7 @@ export function BaseChart({ v3, chartWidth, referenceLines, + zoom, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index ffb446a54..c4fa1316b 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -68,9 +68,11 @@ const CHART_PROPS: Record = { "orientation", "stacked", "referenceLines", + "zoom", ]), line: allKeys()([ "referenceLines", + "zoom", "symbolSize", "showSymbol", "smooth", @@ -78,6 +80,7 @@ const CHART_PROPS: Record = { ]), area: allKeys()([ "referenceLines", + "zoom", "symbolSize", "showSymbol", "smooth", diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 3708d4404..a247345b4 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -42,6 +42,8 @@ export interface OptionBuilderContext { chartWidth?: 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; } export interface CartesianContext extends OptionBuilderContext { @@ -329,11 +331,12 @@ export function buildHorizontalBarOption( ctx.showLegend && hasMultipleSeries ? { top: "bottom", ...legendTextStyle(ui) } : 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: 8, - right: 24, + right: ctx.zoom ? 24 + ZOOM_SLIDER_SIZE + 8 : 24, top: ctx.title ? 40 : 12, bottom: ctx.showLegend && hasMultipleSeries ? 40 : 8, containLabel: true, @@ -581,6 +584,25 @@ function singleDateRange( return { min: timestamp - pad, max: timestamp + pad }; } +/** 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 }, + ]; +} + /** * Reference lines as an ECharts `markLine` on the first series, at values of * the value axis (`yAxis`, or `xAxis` on horizontal bars). @@ -668,6 +690,8 @@ export function buildCartesianOption( // 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); @@ -681,13 +705,23 @@ export function buildCartesianOption( }, legend: ctx.showLegend && hasMultipleSeries - ? { top: "bottom", ...legendTextStyle(ui) } + ? zoom + ? { bottom: ZOOM_SLIDER_SIZE + 12, ...legendTextStyle(ui) } + : { top: "bottom", ...legendTextStyle(ui) } : undefined, + ...(zoom ? { dataZoom: zoomComponents("x") } : {}), grid: { left: "10%", right: "10%", top: ctx.title ? "15%" : "10%", - bottom: ctx.showLegend && hasMultipleSeries ? "20%" : "15%", + // 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.showLegend && hasMultipleSeries + ? "20%" + : "15%", containLabel: true, }, xAxis: { diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 8776ff696..779463d98 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -299,8 +299,17 @@ interface ReferenceLineProps { referenceLines?: ChartReferenceLine[]; } +/** Props of charts with a category or time axis (bar, line, area). */ +interface ZoomProps { + /** + * Zoom along the category or time axis: mouse wheel and drag in the plot, + * plus a slider. Use it for long series. @default false + */ + zoom?: boolean; +} + /** Props specific to bar charts */ -export interface BarChartSpecificProps extends ReferenceLineProps { +export interface BarChartSpecificProps extends ReferenceLineProps, ZoomProps { /** * Bar orientation. When unset, dates are vertical and category labels are * horizontal. With `defaults="v3"`: dates, numbers (such as years) and up @@ -313,7 +322,7 @@ export interface BarChartSpecificProps extends ReferenceLineProps { } /** Props specific to line charts */ -export interface LineChartSpecificProps extends ReferenceLineProps { +export interface LineChartSpecificProps extends ReferenceLineProps, ZoomProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ @@ -328,7 +337,7 @@ export interface LineChartSpecificProps extends ReferenceLineProps { } /** Props specific to area charts */ -export interface AreaChartSpecificProps extends ReferenceLineProps { +export interface AreaChartSpecificProps extends ReferenceLineProps, ZoomProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ From b8c21796ba7fb6e944507b273b5bebad75f226ca Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:34:43 +0000 Subject: [PATCH 046/151] feat(appkit-ui): add showValues to label bars and scatter points The cartesian builder had no label option, so bars could not show their values and scatter points could not be labelled. BarChart and ScatterChart take showValues: bars print their value on top (right on horizontal bars, inside stacked segments) and scatter points print y, formatted like the value axis. Labelling points by a name column is left to the scatter P2 ticket. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 61 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 5 ++ .../src/react/charts/create-chart.tsx | 2 + .../appkit-ui/src/react/charts/options.ts | 34 +++++++++++ packages/appkit-ui/src/react/charts/types.ts | 12 +++- 5 files changed, 112 insertions(+), 2 deletions(-) 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 index a09aa235d..bb5260b63 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -378,3 +378,64 @@ describe("scatter point opacity (SCAT-08)", () => { expect(opacityFor(10000)).toBe(0.2); }); }); + +describe("value labels (C35)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 8fe7e7f8d..2f8678c47 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -266,6 +266,8 @@ export interface BaseChartProps { 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; } // ============================================================================ @@ -309,6 +311,7 @@ export function BaseChart({ defaults, referenceLines, zoom = false, + showValues = false, }: BaseChartProps) { const v3 = defaults === "v3"; // v3: straight lines. Smoothing invents values between points (a one-day @@ -480,6 +483,7 @@ export function BaseChart({ chartWidth, referenceLines, zoom, + showValues, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -574,6 +578,7 @@ export function BaseChart({ chartWidth, referenceLines, zoom, + showValues, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index c4fa1316b..f4bc3bbe7 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -69,6 +69,7 @@ const CHART_PROPS: Record = { "stacked", "referenceLines", "zoom", + "showValues", ]), line: allKeys()([ "referenceLines", @@ -90,6 +91,7 @@ const CHART_PROPS: Record = { scatter: allKeys()([ "symbolSize", "referenceLines", + "showValues", ]), pie: PIE_PROPS, donut: PIE_PROPS, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index a247345b4..69e4e3461 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -44,6 +44,8 @@ export interface OptionBuilderContext { 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; } export interface CartesianContext extends OptionBuilderContext { @@ -380,6 +382,7 @@ export function buildHorizontalBarOption( type: "bar", data: ctx.yDataMap[key], stack: stacked ? "total" : undefined, + label: valueLabel(ctx, key, stacked ? "inside" : "right"), itemStyle: { borderRadius: [0, 4, 4, 0] }, color: ctx.colors[idx % ctx.colors.length], tooltip: ctx.valueFormatter @@ -584,6 +587,29 @@ function singleDateRange( 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.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); + }, + }; +} + /** Height (or width, on horizontal bars) of the zoom slider, in px. */ const ZOOM_SLIDER_SIZE = 18; @@ -821,6 +847,14 @@ export function buildCartesianOption( // when the chart is interactive. No effect on non-line series. triggerLineEvent: isLineLike && interactive ? true : undefined, areaStyle: chartType === "area" ? { opacity: 0.3 } : undefined, + label: + chartType === "bar" || isScatter + ? valueLabel( + ctx, + key, + chartType === "bar" && stacked ? "inside" : "top", + ) + : undefined, stack: stacked && (chartType === "area" || chartType === "bar") ? "total" diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 779463d98..8a3af6de1 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -308,8 +308,15 @@ interface ZoomProps { zoom?: boolean; } +/** Props of charts that can label each mark with its value (bar, scatter). */ +interface ShowValuesProps { + /** Print each bar's (or point's) value next to it. @default false */ + showValues?: boolean; +} + /** Props specific to bar charts */ -export interface BarChartSpecificProps extends ReferenceLineProps, ZoomProps { +export interface BarChartSpecificProps + extends ReferenceLineProps, ZoomProps, ShowValuesProps { /** * Bar orientation. When unset, dates are vertical and category labels are * horizontal. With `defaults="v3"`: dates, numbers (such as years) and up @@ -354,7 +361,8 @@ export interface AreaChartSpecificProps extends ReferenceLineProps, ZoomProps { } /** Props specific to scatter charts */ -export interface ScatterChartSpecificProps extends ReferenceLineProps { +export interface ScatterChartSpecificProps + extends ReferenceLineProps, ShowValuesProps { /** Symbol size @default 8 */ symbolSize?: number; } From 19c1883bec4885bc8a88db1cfb26b19f654bf53c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:37:31 +0000 Subject: [PATCH 047/151] feat(appkit-ui): add per-series type and a second y axis for combo charts Charts drew one series type and one value axis, so bars plus a line, or a measure on its own scale, needed raw options. Bar, line and area charts take series={{ : { type?: "bar" | "line" | "area", axis?: "left" | "right" } }}: a series can be drawn as another type, and axis "right" adds a second value axis (no second set of grid lines) formatted for its first field. Stacked series stack per type and axis when series config is given. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/cartesian-options.test.ts | 39 +++++ .../__tests__/chart-components.test.tsx | 26 +++ packages/appkit-ui/src/react/charts/base.tsx | 6 + .../src/react/charts/create-chart.tsx | 3 + packages/appkit-ui/src/react/charts/index.ts | 1 + .../appkit-ui/src/react/charts/options.ts | 163 ++++++++++-------- packages/appkit-ui/src/react/charts/types.ts | 26 ++- 7 files changed, 193 insertions(+), 71 deletions(-) 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 index bb5260b63..ca8398f74 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/cartesian-options.test.ts @@ -439,3 +439,42 @@ describe("value labels (C35)", () => { expect(option.series[0].label.position).toBe("right"); }); }); + +describe("combo charts and a second y axis (C33)", () => { + 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"]); + }); +}); 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 index 43408a77c..01687a129 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -2,6 +2,7 @@ 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"; @@ -158,3 +159,28 @@ describe("default accessible name (C27)", () => { expect(getByRole("img").getAttribute("aria-label")).toBe("Trend"); }); }); + +describe("combo chart renders (C33)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 2f8678c47..b45a88490 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -55,6 +55,7 @@ import type { ChartData, ChartDefaults, ChartReferenceLine, + ChartSeriesConfig, ChartType, ChartValueFormatter, Orientation, @@ -268,6 +269,8 @@ export interface BaseChartProps { 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; } // ============================================================================ @@ -312,6 +315,7 @@ export function BaseChart({ referenceLines, zoom = false, showValues = false, + series: seriesConfig, }: BaseChartProps) { const v3 = defaults === "v3"; // v3: straight lines. Smoothing invents values between points (a one-day @@ -484,6 +488,7 @@ export function BaseChart({ referenceLines, zoom, showValues, + seriesConfig, }; const isPie = chartType === "pie" || chartType === "donut"; const isRadar = chartType === "radar"; @@ -579,6 +584,7 @@ export function BaseChart({ referenceLines, zoom, showValues, + seriesConfig, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index f4bc3bbe7..ab6487ba1 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -70,10 +70,12 @@ const CHART_PROPS: Record = { "referenceLines", "zoom", "showValues", + "series", ]), line: allKeys()([ "referenceLines", "zoom", + "series", "symbolSize", "showSymbol", "smooth", @@ -82,6 +84,7 @@ const CHART_PROPS: Record = { area: allKeys()([ "referenceLines", "zoom", + "series", "symbolSize", "showSymbol", "smooth", diff --git a/packages/appkit-ui/src/react/charts/index.ts b/packages/appkit-ui/src/react/charts/index.ts index 85718aa49..5ab68cbfa 100644 --- a/packages/appkit-ui/src/react/charts/index.ts +++ b/packages/appkit-ui/src/react/charts/index.ts @@ -112,6 +112,7 @@ export type { ChartDataInput, ChartDefaults, ChartReferenceLine, + ChartSeriesConfig, ChartRow, ChartTransformer, ChartType, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 69e4e3461..0e58f8e7c 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -1,6 +1,7 @@ import { FALLBACK_UI_TOKENS } from "./constants"; import type { ChartReferenceLine, + ChartSeriesConfig, ChartType, ChartUITokens, ChartValue, @@ -46,6 +47,8 @@ export interface OptionBuilderContext { 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 { @@ -173,8 +176,10 @@ function tooltipValueFormatter(formatter: ChartValueFormatter, field: string) { return (value: unknown) => formatter(toMeasureValue(value), field); } -function valueAxisLabel(ctx: OptionBuilderContext) { - const field = ctx.yFields[0]; +function valueAxisLabel( + ctx: OptionBuilderContext, + field: string | undefined = ctx.yFields[0], +) { const formatter = ctx.axisValueFormatter ?? ctx.valueFormatter; return formatter && field ? { formatter: (value: string | number) => formatter(value, field) } @@ -706,8 +711,12 @@ export function buildCartesianOption( } = ctx; const isValueX = ctx.isValueX === true; const hasMultipleSeries = ctx.yFields.length > 1; - const seriesType = chartType === "area" ? "line" : chartType; const isScatter = chartType === "scatter"; + // 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; const isLineLike = chartType === "line" || chartType === "area"; @@ -720,6 +729,18 @@ export function buildCartesianOption( 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])), + }; return { ...buildBaseOption(ctx), @@ -802,77 +823,83 @@ export function buildCartesianOption( : categoryXAxisLabel(ctx, ctx.xData.length, 10), ), }, - yAxis: { - 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)), - }, + 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(cartesianSeries(), ctx, "yAxis"), }; function cartesianSeries(): Record[] { - return ctx.yFields.map((key, idx) => ({ - name: formatLabel(key), - type: seriesType, - 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]) - : ctx.yDataMap[key], - smooth: isLineLike ? smooth : undefined, - connectNulls: isLineLike && ctx.connectNulls ? true : undefined, - // A series with one point has no line to draw: show its symbol. - showSymbol: isLineLike - ? showSymbol || countValues(ctx.yDataMap[key]) <= 1 - : undefined, - // A single bar would fill most of the plot. - ...(chartType === "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. - 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, - label: - chartType === "bar" || isScatter - ? valueLabel( - ctx, - key, - chartType === "bar" && stacked ? "inside" : "top", - ) - : undefined, - stack: - stacked && (chartType === "area" || chartType === "bar") - ? "total" + 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]) + : 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, - itemStyle: - chartType === "bar" - ? { borderRadius: [4, 4, 0, 0] } - : isScatter - ? // Overlapping points stay visible: opacity falls with the count. - { opacity: scatterOpacity(ctx.xData.length) } + // 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. + symbolSize: isScatter || 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, + areaStyle: own === "area" ? { opacity: 0.3 } : undefined, + label: + own === "bar" || isScatter + ? valueLabel(ctx, key, own === "bar" && stacked ? "inside" : "top") : undefined, - color: ctx.colors[idx % ctx.colors.length], - tooltip: ctx.valueFormatter - ? { - valueFormatter: tooltipValueFormatter(ctx.valueFormatter, key), - } - : undefined, - })); + // 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, + }; + }); } } diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 8a3af6de1..38bd6845c 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -299,6 +299,24 @@ interface ReferenceLineProps { referenceLines?: ChartReferenceLine[]; } +/** How one `yKey` is drawn in a combo chart. */ +export interface ChartSeriesConfig { + /** Draw this series as bars, a line or an area. Defaults to the chart type. */ + type?: "bar" | "line" | "area"; + /** Value axis: `"right"` adds a second y axis. @default "left" */ + axis?: "left" | "right"; +} + +/** Props of charts that can mix series types and value axes (bar, line, area). */ +interface ComboProps { + /** + * 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. + */ + series?: Record; +} + /** Props of charts with a category or time axis (bar, line, area). */ interface ZoomProps { /** @@ -316,7 +334,7 @@ interface ShowValuesProps { /** Props specific to bar charts */ export interface BarChartSpecificProps - extends ReferenceLineProps, ZoomProps, ShowValuesProps { + extends ReferenceLineProps, ZoomProps, ShowValuesProps, ComboProps { /** * Bar orientation. When unset, dates are vertical and category labels are * horizontal. With `defaults="v3"`: dates, numbers (such as years) and up @@ -329,7 +347,8 @@ export interface BarChartSpecificProps } /** Props specific to line charts */ -export interface LineChartSpecificProps extends ReferenceLineProps, ZoomProps { +export interface LineChartSpecificProps + extends ReferenceLineProps, ZoomProps, ComboProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ @@ -344,7 +363,8 @@ export interface LineChartSpecificProps extends ReferenceLineProps, ZoomProps { } /** Props specific to area charts */ -export interface AreaChartSpecificProps extends ReferenceLineProps, ZoomProps { +export interface AreaChartSpecificProps + extends ReferenceLineProps, ZoomProps, ComboProps { /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ From d7ca3f38d7f56b11d5ae2152d580b598f4fddd4c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:45:34 +0000 Subject: [PATCH 048/151] fix(appkit-ui): onDataClick returns the source row and the original x value Clicks on a date axis returned an empty name (bars, symbols) or epoch ms (line strokes), scatter dataIndex counted plotted points in x order, pie/heatmap/radar seriesName was an ECharts NUL placeholder, and a radar click did not say which metric. Normalization now tracks the source row of each x position (and of each heatmap cell); a new click resolver sets `name` to the x value as it is in the row, adds `row` (Arrow rows as plain objects) to ChartClickDatum, maps scatter points back to row order, names pie/heatmap series after the yKey, and hit-tests radar clicks to the nearest spoke (name = metric, value = that metric, seriesName = the polygon). Long rows pivoted with seriesKey get no row. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/click.test.tsx | 172 ++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 67 ++++++- packages/appkit-ui/src/react/charts/click.ts | 184 ++++++++++++++++++ .../appkit-ui/src/react/charts/normalize.ts | 112 +++++++---- .../appkit-ui/src/react/charts/options.ts | 28 ++- packages/appkit-ui/src/react/charts/types.ts | 18 +- 6 files changed, 529 insertions(+), 52 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/click.test.tsx create mode 100644 packages/appkit-ui/src/react/charts/click.ts 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index b45a88490..bba8dd9d8 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -30,6 +30,7 @@ import { LegacyGridContainLabel } from "echarts/features"; import { CanvasRenderer } from "echarts/renderers"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { type ClickContext, resolveClickDatum } from "./click"; import { chartSizeStyle } from "./constants"; import { normalizeChartData, @@ -61,7 +62,12 @@ import type { Orientation, XAxisType, } from "./types"; -import { formatCompactNumber, formatFullNumber, mapToDatum } from "./utils"; +import { + formatCompactNumber, + formatFullNumber, + formatLabel, + mapToDatum, +} from "./utils"; // ============================================================================ // ECharts Registration (modular imports for tree-shaking) @@ -145,6 +151,29 @@ function scatterXError(normalized: { 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; + } +} + // ============================================================================ // Bar Orientation // ============================================================================ @@ -604,6 +633,27 @@ 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: normalized.yFields.map((f) => formatLabel(f)), + }), + [chartType, data, normalized], + ); + 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 @@ -613,8 +663,21 @@ export function BaseChart({ 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 && 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..af8a64331 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/click.ts @@ -0,0 +1,184 @@ +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[]; +} + +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]); + } + if (ctx.chartType === "scatter") result.dataIndex = rowIdx ?? position; + return result; +} diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index ae57006a1..360e2fada 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -429,6 +429,48 @@ function pivotLongRows( return { rows: Array.from(byX.values()), seriesNames }; } +/** 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[]; +} { + 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") { + 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[], + }; +} + function isArrowTemporalField(table: Table, key: string): boolean { const field = table.schema.fields.find((f) => f.name === key); if (!field) return false; @@ -464,7 +506,7 @@ export function normalizeChartData( seriesKey, resolvedYKeys[0], ); - return normalizeChartData( + const pivoted = normalizeChartData( pivot.rows, resolvedXKey, pivot.seriesNames, @@ -474,6 +516,8 @@ export function normalizeChartData( seriesKey: undefined, }, ); + // Row indices point at the pivoted rows, not the caller's rows. + return { ...pivoted, rowIndex: undefined }; } if (isArrowTable(data)) { @@ -505,28 +549,17 @@ export function normalizeChartData( yDataMap[key] = toChartArray(rawYDataMap[key] ?? [], keepNulls); } - if (chartType === "timeseries") { - ({ xData, yDataMap } = sortTimeSeriesAscending( - xData, - yDataMap, - resolvedYKeys, - )); - } else if ( - xAxisType === "value" && - xData.length > 0 && - xData.every(isNumericValue) - ) { - // Only a numeric axis is sorted; category values keep their row order - // and their text ("007" stays "007"). - - ({ xData, yDataMap } = sortNumericAscending( - xData, - yDataMap, - resolvedYKeys, - )); - } + let rowIndex: number[]; + ({ xData, yDataMap, rowIndex } = sortByXAxis( + xData, + yDataMap, + resolvedYKeys, + chartType, + xAxisType, + )); return { + rowIndex, xData, yDataMap, xField: resolvedXKey, @@ -568,28 +601,17 @@ export function normalizeChartData( ); } - if (chartType === "timeseries") { - ({ xData, yDataMap } = sortTimeSeriesAscending( - xData, - yDataMap, - resolvedYKeys, - )); - } else if ( - xAxisType === "value" && - xData.length > 0 && - xData.every(isNumericValue) - ) { - // Only a numeric axis is sorted; category values keep their row order - // and their text ("007" stays "007"). - - ({ xData, yDataMap } = sortNumericAscending( - xData, - yDataMap, - resolvedYKeys, - )); - } + let rowIndex: number[]; + ({ xData, yDataMap, rowIndex } = sortByXAxis( + xData, + yDataMap, + resolvedYKeys, + chartType, + xAxisType, + )); return { + rowIndex, xData, yDataMap, xField: resolvedXKey, @@ -616,6 +638,8 @@ 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[]; /** Min value in the data */ min: number; /** Max value in the data */ @@ -651,6 +675,7 @@ export function normalizeHeatmapData( chartType: "categorical", yAxisData: [], heatmapData: [], + cellRowIndex: [], min: 0, max: 0, }; @@ -692,11 +717,12 @@ export function normalizeHeatmapData( // Build heatmap data and track min/max const heatmapData: [number, number, number][] = []; + const cellRowIndex: number[] = []; 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 rawValue = row[resolvedValueKey]; @@ -720,6 +746,7 @@ export function normalizeHeatmapData( if (xIdx !== undefined && yIdx !== undefined) { heatmapData.push([xIdx, yIdx, numValue]); + cellRowIndex.push(rowIdx); min = Math.min(min, numValue); max = Math.max(max, numValue); } @@ -744,6 +771,7 @@ export function normalizeHeatmapData( chartType: "categorical", yAxisData, heatmapData, + cellRowIndex, min, max, }; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 0e58f8e7c..af6c14a08 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -253,9 +253,11 @@ export function buildPieOption( labelPosition: string, ): Record { const ui = ctx.ui ?? FALLBACK_UI_TOKENS; + // `sourceIndex` maps a clicked slice back to its x position. const pieData = ctx.xData.map((name, i) => ({ name: String(name), value: ctx.yDataMap[ctx.yFields[0]]?.[i] ?? 0, + sourceIndex: i, })); const isDonut = chartType === "donut" || innerRadius > 0; @@ -290,6 +292,7 @@ export function buildPieOption( series: [ { type: "pie", + ...(valueField ? { name: formatLabel(valueField) } : {}), radius: isDonut ? [`${innerRadius || 40}%`, "70%"] : "70%", center: ["60%", "50%"], // Keep very small categories pointer-selectable. ECharts still reports @@ -487,6 +490,7 @@ export function buildHeatmapOption( series: [ { type: "heatmap", + ...(valueField ? { name: formatLabel(valueField) } : {}), data: ctx.heatmapData, label: { show: ctx.showLabels, @@ -560,17 +564,27 @@ function scatterOpacity(count: number): number { 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][] { - const points: [number, number][] = []; - for (let i = 0; i < xData.length; i++) { - const x = toFiniteNumber(xData[i]); - const y = toFiniteNumber(yData[i]); - if (x !== null && y !== null) points.push([x, y]); - } - return points; + return scatterPointIndices(xData, yData).map((i) => [ + toFiniteNumber(xData[i]) as number, + toFiniteNumber(yData[i]) as number, + ]); } const DAY_MS = 24 * 60 * 60 * 1000; diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 38bd6845c..99a55dffc 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -198,7 +198,11 @@ export interface ChartBaseProps { * dimension value of the clicked element. */ export interface ChartClickDatum { - /** Category label of the clicked element — the dimension value in the common cross-filter case. */ + /** + * The dimension value of the clicked element, as it is in the data: the + * category, the original date string on a time axis, the slice name, the + * heatmap column, or the radar metric nearest the click. + */ name: string; /** * The datum's scalar value: @@ -215,7 +219,14 @@ export interface ChartClickDatum { value: number | string | null; x?: number | string; y?: number | string; + /** Series label (the `yKey`, formatted). Radar: the clicked polygon's series. */ seriesName?: string; + /** + * The source row behind the clicked element (Arrow rows as plain objects). + * Absent for synthetic marks such as a pie's "Other" slice, and for long + * rows pivoted with `seriesKey`. + */ + row?: Record; dataIndex: number; seriesIndex: number; // Untouched ECharts event params. @@ -448,6 +459,11 @@ export interface NormalizedChartDataBase { xAxisType?: XAxisType; /** True when x holds DATE values (no time of day). */ xDateOnly?: boolean; + /** + * For each `xData` position, the index of the source row it came from + * (normalization sorts time and numeric axes). Absent for pivoted long rows. + */ + rowIndex?: number[]; } /** Normalized chart data for rendering (standard charts) */ From cca39099be3c1a7f7e36173de4f9ce48a6532004 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:47:50 +0000 Subject: [PATCH 049/151] fix(appkit-ui): pie and donut show an error for negative values A negative value was not drawn but kept its legend entry (with another slice color), and shares were computed over the positive values only (60, -20, 40 showed as 60% and 40%). Pie and donut now render an error state naming the column and suggesting a BarChart, and log console.error. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 28 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 26 +++++++++++++++-- 2 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx 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..ae4cb67e6 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -0,0 +1,28 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"; + +import { PieChart } from "../pie"; +import { installEChartsEnv } from "./helpers/echarts-env"; + +beforeAll(() => installEChartsEnv()); +afterEach(() => cleanup()); + +describe("negative values (PIE-01)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index bba8dd9d8..cf92db385 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -174,6 +174,21 @@ function radarGeometry(instance: ECharts) { } } +/** + * 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.`; +} + // ============================================================================ // Bar Orientation // ============================================================================ @@ -447,11 +462,18 @@ export function BaseChart({ ); // Data a chart can't draw is reported instead of drawing an empty plot. + const isPieChart = chartType === "pie" || chartType === "donut"; const chartError = useMemo( () => - keyError ?? (chartType === "scatter" ? scatterXError(normalized) : null), - [keyError, chartType, normalized], + keyError ?? + (chartType === "scatter" + ? scatterXError(normalized) + : isPieChart && "yDataMap" in normalized + ? pieValueError(normalized) + : null), + [keyError, chartType, isPieChart, normalized], ); + useEffect(() => { if (chartError) { console.error(`[appkit-ui] ${chartType} chart: ${chartError}`); From 2f6070fd32d2233472a5603f6023d1304fe74c91 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:48:17 +0000 Subject: [PATCH 050/151] fix(appkit-ui): all-zero pie and donut show the empty state All-zero data drew a full ring of equal slices labelled "0%". A pie or donut whose values are all 0, null or missing now shows the "No data" state. An unknown yKey already shows the key error from C3; the test covers both. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 67 ++++++++++++++++++- packages/appkit-ui/src/react/charts/base.tsx | 16 ++++- 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index ae4cb67e6..d78e24745 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -1,12 +1,32 @@ -import { cleanup, render } from "@testing-library/react"; +import { cleanup, render, waitFor } from "@testing-library/react"; import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"; -import { PieChart } from "../pie"; -import { installEChartsEnv } from "./helpers/echarts-env"; +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 }[]; + graphic?: unknown[]; +}; + +async function pieOption(container: HTMLElement) { + return waitFor(() => { + const option = chartOption(container); + expect(option).toBeDefined(); + return option as PieOption; + }); +} + describe("negative values (PIE-01)", () => { test("show an error instead of dropping the slice", () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); @@ -26,3 +46,44 @@ describe("negative values (PIE-01)", () => { error.mockRestore(); }); }); + +describe("nothing to draw (PIE-02)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index cf92db385..6c5623ca1 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -189,6 +189,16 @@ function pieValueError(normalized: { 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); +} + // ============================================================================ // Bar Orientation // ============================================================================ @@ -473,7 +483,9 @@ export function BaseChart({ : null), [keyError, chartType, isPieChart, normalized], ); - + // All-zero pies used to draw a full ring of equal "0%" slices. + const pieEmpty = + isPieChart && "yDataMap" in normalized && pieIsEmpty(normalized); useEffect(() => { if (chartError) { console.error(`[appkit-ui] ${chartType} chart: ${chartError}`); @@ -725,7 +737,7 @@ export function BaseChart({ ); } - if (!option) { + if (!option || pieEmpty) { return (
Date: Tue, 1 Dec 2026 21:51:22 +0000 Subject: [PATCH 051/151] test(appkit-ui): expect sourceIndex on pie data items X2 adds `sourceIndex` to each pie data item so a click maps back to its row; the buildPieOption shape test still expected { name, value } only. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- packages/appkit-ui/src/react/charts/__tests__/options.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 d0b503bb3..263a71984 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -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, }); }); From 876fbf137c22f9b3aca1e045fa763c9b86b6276b Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:52:04 +0000 Subject: [PATCH 052/151] feat(appkit-ui): v3 pie and donut defaults: legend with share, no slice labels With defaults="v3": slice labels are off (they overlapped and the largest was cut to "Ent..."), the legend sits below the pie, scrolls, and shows name, value and share; slices are sorted largest first and past 5 the tail is summed into one "Other" slice (top 4 plus Other); the pie is centred; and a donut shows the formatted total in the hole. Without v3 the pie is unchanged. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 54 ++++++++- packages/appkit-ui/src/react/charts/base.tsx | 6 +- .../appkit-ui/src/react/charts/options.ts | 114 ++++++++++++++++-- 3 files changed, 161 insertions(+), 13 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index d78e24745..1fe9d0908 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -16,7 +16,7 @@ type PieOption = { label: { show: boolean }; }[]; legend?: { formatter?: unknown; type?: string }[]; - graphic?: unknown[]; + title?: unknown; }; async function pieOption(container: HTMLElement) { @@ -87,3 +87,55 @@ describe("nothing to draw (PIE-02)", () => { 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 (C17)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 6c5623ca1..56930c37f 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -355,7 +355,7 @@ export function BaseChart({ symbolSize = 8, showArea = true, innerRadius = 0, - showLabels = true, + showLabels: showLabelsProp, labelPosition = "outside", yAxisKey, min, @@ -372,6 +372,10 @@ export function BaseChart({ series: seriesConfig, }: BaseChartProps) { const v3 = defaults === "v3"; + // 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; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index af6c14a08..f03e8baa8 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -245,27 +245,110 @@ 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; + +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 }]; +} + +/** 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, showLabels: boolean, labelPosition: string, + extras: PieOptionExtras = {}, ): Record { const ui = ctx.ui ?? FALLBACK_UI_TOKENS; + const valueField = ctx.yFields[0]; // `sourceIndex` maps a clicked slice back to its x position. - const pieData = ctx.xData.map((name, i) => ({ + 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, })); + const pieData = ctx.v3 ? v3Slices(rawSlices) : rawSlices; const isDonut = chartType === "donut" || innerRadius > 0; - const valueField = ctx.yFields[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; + return `${name} ${formatValue(sliceValue(slice))} ${share}%`; + }; + + const centerLabel = + extras.centerLabel ?? (ctx.v3 && chartType === "donut" ? true : undefined); + const centerText = + isDonut && centerLabel + ? centerLabel === true + ? formatValue(total) + : centerLabel + : undefined; + + const base = buildBaseOption(ctx); + const center = ctx.v3 + ? ctx.showLegend + ? ["50%", "44%"] + : ["50%", "50%"] + : ["60%", "50%"]; return { - ...buildBaseOption(ctx), + ...base, + ...(centerText !== undefined + ? { + title: [ + ...(base.title ? [base.title] : []), + { + text: centerText, + left: center[0], + top: center[1], + textAlign: "center", + textVerticalAlign: "middle", + textStyle: { color: ui.axisTitle, fontSize: 20, fontWeight: 600 }, + }, + ], + } + : {}), tooltip: { ...tooltipTokens(ui), trigger: "item", @@ -282,19 +365,28 @@ export function buildPieOption( : "{b}: {c} ({d}%)", }, legend: ctx.showLegend - ? { - orient: "vertical", - left: "left", - top: "middle", - ...legendTextStyle(ui), - } + ? ctx.v3 + ? { + type: "scroll", + orient: "horizontal", + left: "center", + bottom: 0, + formatter: v3LegendFormatter, + ...legendTextStyle(ui), + } + : { + orient: "vertical", + left: "left", + top: "middle", + ...legendTextStyle(ui), + } : undefined, series: [ { type: "pie", ...(valueField ? { name: formatLabel(valueField) } : {}), radius: isDonut ? [`${innerRadius || 40}%`, "70%"] : "70%", - center: ["60%", "50%"], + center, // 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. From f9efab650d8033e4bdc5d4f78effb80230fd789b Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:53:21 +0000 Subject: [PATCH 053/151] fix(appkit-ui): pie drops zero and missing slices and draws tiny ones to scale `minAngle: 3` drew a 0.1% slice about eight times too large and gave zero and null values a visible sliver labelled "0%". Slices with no positive value are now left out (and out of the legend), and minAngle is gone, so every slice is drawn at its true share. v3 groups the smallest slices as "Other" (C17). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/options.test.ts | 9 +++++---- .../src/react/charts/__tests__/pie.test.tsx | 20 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 9 ++++----- 3 files changed, 29 insertions(+), 9 deletions(-) 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 263a71984..8f9e6622d 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -636,14 +636,15 @@ 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", () => { diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index 1fe9d0908..431789876 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -139,3 +139,23 @@ describe("v3 pie defaults (C17)", () => { expect(option.series[0].label.show).toBe(true); }); }); + +describe("small and zero slices (PIE-03)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index f03e8baa8..a4d513a1d 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -296,7 +296,10 @@ export function buildPieOption( value: ctx.yDataMap[valueField]?.[i] ?? 0, sourceIndex: i, })); - const pieData = ctx.v3 ? v3Slices(rawSlices) : rawSlices; + // 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 formatter = ctx.valueFormatter; @@ -387,10 +390,6 @@ export function buildPieOption( ...(valueField ? { name: formatLabel(valueField) } : {}), radius: isDonut ? [`${innerRadius || 40}%`, "70%"] : "70%", center, - // 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, data: pieData, label: { show: showLabels, From c6682b7c9a2b52ea508820ff40cf4983aa2dd769 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:54:52 +0000 Subject: [PATCH 054/151] fix(appkit-ui): clamp the donut hole and let innerRadius={0} mean no hole innerRadius was not clamped: from 70 up the inner radius passed the fixed outer radius (70%) and at 100 the ring overflowed the card; negative values were passed through; and on DonutChart `innerRadius={0}` silently became 40. The hole is now clamped to 0 up to 63 (90% of the outer radius), and DonutChart defaults to 40 only when innerRadius is unset. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/options.test.ts | 6 ++-- .../src/react/charts/__tests__/pie.test.tsx | 23 +++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 4 +-- .../appkit-ui/src/react/charts/options.ts | 29 +++++++++++++++++-- packages/appkit-ui/src/react/charts/types.ts | 6 +++- 5 files changed, 60 insertions(+), 8 deletions(-) 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 8f9e6622d..35e589224 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -649,9 +649,11 @@ describe("buildPieOption", () => { 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%"]); }); diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index 431789876..2b66e09a7 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -159,3 +159,26 @@ describe("small and zero slices (PIE-03)", () => { expect(option.series[0].minAngle ?? 0).toBe(0); }); }); + +describe("hole radius (PIE-05)", () => { + 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%", + ]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 56930c37f..a82541759 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -271,7 +271,7 @@ export interface BaseChartProps { 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; @@ -354,7 +354,7 @@ export function BaseChart({ stacked = false, symbolSize = 8, showArea = true, - innerRadius = 0, + innerRadius, showLabels: showLabelsProp, labelPosition = "outside", yAxisKey, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index a4d513a1d..1450194b4 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -248,6 +248,26 @@ export function buildRadarOption( /** 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; @@ -283,7 +303,7 @@ interface PieOptionExtras { export function buildPieOption( ctx: OptionBuilderContext, chartType: "pie" | "donut", - innerRadius: number, + innerRadius: number | undefined, showLabels: boolean, labelPosition: string, extras: PieOptionExtras = {}, @@ -301,7 +321,8 @@ export function buildPieOption( const drawn = rawSlices.filter((slice) => sliceValue(slice) > 0); const pieData = ctx.v3 ? v3Slices(drawn) : drawn; - const isDonut = chartType === "donut" || innerRadius > 0; + 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); @@ -388,7 +409,9 @@ export function buildPieOption( { type: "pie", ...(valueField ? { name: formatLabel(valueField) } : {}), - radius: isDonut ? [`${innerRadius || 40}%`, "70%"] : "70%", + radius: isDonut + ? [`${hole}%`, `${PIE_OUTER_RADIUS}%`] + : `${PIE_OUTER_RADIUS}%`, center, data: pieData, label: { diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 99a55dffc..ef7d4e671 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -400,7 +400,11 @@ export interface ScatterChartSpecificProps /** Props specific to pie/donut charts */ export interface PieChartSpecificProps { - /** Inner radius for donut charts (0-100%) @default 0 */ + /** + * 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. + * @default 0 (40 on DonutChart) + */ innerRadius?: number; /** Show labels on slices @default true */ showLabels?: boolean; From 40a7928027b9f0928a9ae3da3d1a67c0f45be89e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:56:26 +0000 Subject: [PATCH 055/151] fix(appkit-ui): place the pie legend by size, truncate names, centre the pie The pie legend had no width limit: long names ran over the ring and the hole, at 240 px the legend lay on the slices, and with showLegend={false} the pie still sat at 60% with an empty strip. The chart now measures its height as well as its width. A side legend takes at most 30% of the width, names are truncated to fit (full name on hover), and the pie is centred in the rest; below 360 px wide, or on a tall chart, the legend goes underneath; without a legend the pie is centred. The legend scrolls. Before the first measurement the old layout is kept. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 55 +++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 5 + .../appkit-ui/src/react/charts/options.ts | 91 +++++++++++++++---- 3 files changed, 131 insertions(+), 20 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index 2b66e09a7..2b4fc375f 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -1,6 +1,7 @@ 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"; @@ -182,3 +183,57 @@ describe("hole radius (PIE-05)", () => { ]); }); }); + +describe("legend layout (PIE-06)", () => { + 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%"]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index a82541759..b0c749a81 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -408,6 +408,7 @@ export function BaseChart({ // 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 @@ -430,7 +431,9 @@ export function BaseChart({ 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; @@ -552,6 +555,7 @@ export function BaseChart({ xDateOnly, v3, chartWidth, + chartHeight, referenceLines, zoom, showValues, @@ -648,6 +652,7 @@ export function BaseChart({ interactive, v3, chartWidth, + chartHeight, referenceLines, zoom, showValues, diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 1450194b4..6264d511d 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -41,6 +41,8 @@ export interface OptionBuilderContext { 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. */ @@ -294,6 +296,60 @@ function v3Slices(slices: PieSlice[]): PieSlice[] { 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 pieLayout(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), + }; +} + /** Pie or donut extras beyond the shared props. */ interface PieOptionExtras { /** Text in the donut hole; `true` shows the formatted total. */ @@ -350,11 +406,8 @@ export function buildPieOption( : undefined; const base = buildBaseOption(ctx); - const center = ctx.v3 - ? ctx.showLegend - ? ["50%", "44%"] - : ["50%", "50%"] - : ["60%", "50%"]; + const layout = pieLayout(ctx); + const center = layout.center; return { ...base, @@ -389,21 +442,19 @@ export function buildPieOption( : "{b}: {c} ({d}%)", }, legend: ctx.showLegend - ? ctx.v3 - ? { - type: "scroll", - orient: "horizontal", - left: "center", - bottom: 0, - formatter: v3LegendFormatter, - ...legendTextStyle(ui), - } - : { - 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 }, + } : undefined, series: [ { From 8a459ae5d88059a792d12fff007480537371f688 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 21:58:25 +0000 Subject: [PATCH 056/151] feat(appkit-ui): centerLabel prop: donut hole text sized to fit The donut skill recipe overlaid the total with a fixed 24 px font, which spills across the ring once the total has seven digits. New `centerLabel` on PieChart and DonutChart: a string, or `true` for the formatted total. The font shrinks with the measured hole and the text length (11 to 24 px), and a total that still does not fit is compacted ("9.7M"). It is the default on a v3 DonutChart (C17). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 39 +++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 5 ++ .../src/react/charts/create-chart.tsx | 1 + .../appkit-ui/src/react/charts/options.ts | 70 ++++++++++++++++--- packages/appkit-ui/src/react/charts/types.ts | 6 ++ 5 files changed, 112 insertions(+), 9 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index 2b4fc375f..dfb53ff71 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -237,3 +237,42 @@ describe("legend layout (PIE-06)", () => { expect(opt.series[0].center).toEqual(["50%", "50%"]); }); }); + +describe("donut hole text (PIE-07)", () => { + 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", + ); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index b0c749a81..110dac64a 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -277,6 +277,8 @@ export interface BaseChartProps { 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 */ @@ -357,6 +359,7 @@ export function BaseChart({ innerRadius, showLabels: showLabelsProp, labelPosition = "outside", + centerLabel, yAxisKey, min, max, @@ -606,6 +609,7 @@ export function BaseChart({ innerRadius, showLabels, labelPosition, + { centerLabel }, ); } else if (isHorizontal) { opt = buildHorizontalBarOption(baseCtx, stacked); @@ -638,6 +642,7 @@ export function BaseChart({ innerRadius, showLabels, labelPosition, + centerLabel, stacked, smooth, connectNulls, diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index ab6487ba1..8965a4745 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -60,6 +60,7 @@ const PIE_PROPS = allKeys()([ "innerRadius", "showLabels", "labelPosition", + "centerLabel", ]); /** Props each chart type reads, beyond the shared ones. */ diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 6264d511d..3e34904be 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -10,6 +10,7 @@ import type { import { createTimeSeriesData, escapeHtml, + formatCompactNumber, formatLabel, formatLocalDate, formatTimeLabel, @@ -350,6 +351,50 @@ function pieLayout(ctx: OptionBuilderContext): { }; } +/** 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; + +/** + * 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) { + return { + text: content.text, + 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. */ @@ -398,16 +443,19 @@ export function buildPieOption( const centerLabel = extras.centerLabel ?? (ctx.v3 && chartType === "donut" ? true : undefined); - const centerText = + const center = centerFit( isDonut && centerLabel ? centerLabel === true - ? formatValue(total) - : centerLabel - : undefined; + ? { total, full: formatValue(total) } + : { text: centerLabel } + : undefined, + hole, + ctx, + ); + const centerText = center?.text; const base = buildBaseOption(ctx); const layout = pieLayout(ctx); - const center = layout.center; return { ...base, @@ -417,11 +465,15 @@ export function buildPieOption( ...(base.title ? [base.title] : []), { text: centerText, - left: center[0], - top: center[1], + left: layout.center[0], + top: layout.center[1], textAlign: "center", textVerticalAlign: "middle", - textStyle: { color: ui.axisTitle, fontSize: 20, fontWeight: 600 }, + textStyle: { + color: ui.axisTitle, + fontSize: center?.fontSize, + fontWeight: 600, + }, }, ], } @@ -463,7 +515,7 @@ export function buildPieOption( radius: isDonut ? [`${hole}%`, `${PIE_OUTER_RADIUS}%`] : `${PIE_OUTER_RADIUS}%`, - center, + center: layout.center, data: pieData, label: { show: showLabels, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index ef7d4e671..5815902e6 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -410,6 +410,12 @@ export interface PieChartSpecificProps { showLabels?: boolean; /** Label position @default "outside" */ labelPosition?: "outside" | "inside" | "center"; + /** + * 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. @default true on a v3 DonutChart + */ + centerLabel?: string | boolean; } /** Props specific to radar charts */ From 46bf3e40e98c5482716d6a62e6cc550ee1d353f8 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:00:00 +0000 Subject: [PATCH 057/151] fix(appkit-ui): scrolling one-row legend and a warning past 8 series The legend had no scroll and sat in a fixed 20% band, so twelve series wrapped over the x axis labels; colors repeat after eight series or slices with no word. Series legends (cartesian, horizontal bar, radar) now scroll in one row, with a 36 px band reserved under cartesian plots, and the chart logs a console.warn past 8 series or pie slices. With defaults="v3" pies already group the tail as "Other" (C17); grouping series into "Other" on line and bar charts is not done, since summing series changes their meaning. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 30 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 20 +++++++++++++ .../appkit-ui/src/react/charts/options.ts | 21 ++++++++----- 3 files changed, 64 insertions(+), 7 deletions(-) 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 index 01687a129..3489fce61 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -184,3 +184,33 @@ describe("combo chart renders (C33)", () => { expect(option?.series[1].yAxisIndex).toBe(1); }); }); + +describe("many series (C18)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 110dac64a..268b59633 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -199,6 +199,9 @@ function pieIsEmpty(normalized: { return !values.some((v) => v !== null && Number(v) > 0); } +/** Colors in the categorical palette before they repeat. */ +const MAX_DISTINCT_COLORS = 8; + // ============================================================================ // Bar Orientation // ============================================================================ @@ -502,6 +505,23 @@ export function BaseChart({ } }, [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]); + // 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; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 3e34904be..4efd3d97b 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -153,10 +153,17 @@ function categoryYLabelWidth(ctx: OptionBuilderContext): number { return Math.round(Math.min(220, Math.max(60, ctx.chartWidth * 0.3))); } -function legendTextStyle(ui: ChartUITokens) { - return { textStyle: { color: ui.axisTitle } }; +/** + * 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) { + return { type: "scroll", textStyle: { color: ui.axisTitle } }; } +/** 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, @@ -208,7 +215,7 @@ export function buildRadarOption( tooltip: { ...tooltipTokens(ui), trigger: "item" }, legend: ctx.showLegend && ctx.yFields.length > 1 - ? { top: "bottom", ...legendTextStyle(ui) } + ? { top: "bottom", ...seriesLegend(ui) } : undefined, radar: { indicator: ctx.xData.map((name) => ({ @@ -556,7 +563,7 @@ export function buildHorizontalBarOption( }, legend: ctx.showLegend && hasMultipleSeries - ? { top: "bottom", ...legendTextStyle(ui) } + ? { top: "bottom", ...seriesLegend(ui) } : undefined, ...(ctx.zoom ? { dataZoom: zoomComponents("y") } : {}), // Pixel margins, with the label space reserved by containLabel: the old @@ -984,8 +991,8 @@ export function buildCartesianOption( legend: ctx.showLegend && hasMultipleSeries ? zoom - ? { bottom: ZOOM_SLIDER_SIZE + 12, ...legendTextStyle(ui) } - : { top: "bottom", ...legendTextStyle(ui) } + ? { bottom: ZOOM_SLIDER_SIZE + 12, ...seriesLegend(ui) } + : { top: "bottom", ...seriesLegend(ui) } : undefined, ...(zoom ? { dataZoom: zoomComponents("x") } : {}), grid: { @@ -998,7 +1005,7 @@ export function buildCartesianOption( ? ZOOM_SLIDER_SIZE + 52 : ZOOM_SLIDER_SIZE + 20 : ctx.showLegend && hasMultipleSeries - ? "20%" + ? LEGEND_BAND : "15%", containLabel: true, }, From b9f2e03627326a1a2b68df4fe2dcf140a8106873 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:01:57 +0000 Subject: [PATCH 058/151] fix(appkit-ui): radar gives each metric its own rim when scales differ Radar used one maximum (1.2 x the largest value) for every spoke, so metrics on smaller scales collapsed to the centre. When the largest values of the metrics differ by more than 10x, each spoke now gets its own rim; otherwise they share one. Rims are the value rounded up to a nice number (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8 x 10^k) instead of x1.2, so scores out of 100 get a rim of 100. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/options.test.ts | 14 ++++++- .../appkit-ui/src/react/charts/options.ts | 41 ++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-) 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 35e589224..8dc5e030e 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/options.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/options.test.ts @@ -719,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 (C20)", () => { + 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", () => { diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 4efd3d97b..403e9abce 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -200,15 +200,46 @@ function valueAxisLabel( // 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); +} + export function buildRadarOption( ctx: OptionBuilderContext, showArea = true, ): 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 axisMax = radarAxisMaxima(ctx); return { ...buildBaseOption(ctx), @@ -218,9 +249,9 @@ export function buildRadarOption( ? { top: "bottom", ...seriesLegend(ui) } : undefined, radar: { - indicator: ctx.xData.map((name) => ({ + indicator: ctx.xData.map((name, i) => ({ name: String(name), - max: maxValue * 1.2, + max: axisMax[i], })), shape: "polygon", axisName: { color: ui.axisTitle }, From da15891c2596c77a7eb798b75e092384d0395116 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:03:37 +0000 Subject: [PATCH 059/151] feat(appkit-ui): radar max prop and ring value labels A known maximum could not be set (the rim was the data maximum), and the rings had no values, so nothing could be read off the chart. RadarChart now takes `max`: one number for every metric (e.g. 100 for scores) or one per metric in row order. Ring values are shown on the first spoke when all spokes share a scale and on every spoke when they do not, formatted like value axes. The X8 ignored-prop test now uses yAxisKey, since max is a radar prop. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/chart-components.test.tsx | 4 +- .../src/react/charts/__tests__/radar.test.tsx | 61 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 7 ++- .../src/react/charts/create-chart.tsx | 2 +- .../appkit-ui/src/react/charts/options.ts | 24 +++++++- packages/appkit-ui/src/react/charts/types.ts | 5 ++ 6 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx 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 index 3489fce61..6cbd0f510 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/chart-components.test.tsx @@ -37,7 +37,7 @@ describe("chart-specific props (X8)", () => { test("a prop the chart type ignores warns in development", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const props = { min: 0, max: 100 } as Record; + const props = { min: 0, yAxisKey: "x" } as Record; render( { ); expect( warn.mock.calls.some((c) => - String(c[0]).includes("RadarChart ignores `min`, `max`"), + String(c[0]).includes("RadarChart ignores `min`, `yAxisKey`"), ), ).toBe(true); }); 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..446bed6fc --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -0,0 +1,61 @@ +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 (RAD-02)", () => { + 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]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 268b59633..d4e0fcd63 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -287,7 +287,8 @@ export interface BaseChartProps { /** 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. * @@ -617,11 +618,11 @@ export function BaseChart({ yAxisData: heatmapNorm.yAxisData, heatmapData: heatmapNorm.heatmapData, min: min ?? heatmapNorm.min, - max: max ?? heatmapNorm.max, + max: typeof max === "number" ? max : heatmapNorm.max, showLabels, }); } else if (isRadar) { - opt = buildRadarOption(baseCtx, showArea); + opt = buildRadarOption(baseCtx, showArea, max); } else if (isPie) { opt = buildPieOption( baseCtx, diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index 8965a4745..3cdeb731c 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -99,7 +99,7 @@ const CHART_PROPS: Record = { ]), pie: PIE_PROPS, donut: PIE_PROPS, - radar: allKeys()(["showArea"]), + radar: allKeys()(["showArea", "max"]), heatmap: allKeys()([ "yAxisKey", "min", diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 403e9abce..eccf9b305 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -236,10 +236,31 @@ function radarAxisMaxima(ctx: OptionBuilderContext): number[] { export function buildRadarOption( ctx: OptionBuilderContext, showArea = true, + max?: number | readonly number[], ): Record { const ui = ctx.ui ?? FALLBACK_UI_TOKENS; const formatter = ctx.valueFormatter; - const axisMax = radarAxisMaxima(ctx); + 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), @@ -252,6 +273,7 @@ export function buildRadarOption( indicator: ctx.xData.map((name, i) => ({ name: String(name), max: axisMax[i], + ...(i === 0 || !sharedScale ? { axisLabel: ringLabel } : {}), })), shape: "polygon", axisName: { color: ui.axisTitle }, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 5815902e6..28b8040ca 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -422,6 +422,11 @@ export interface PieChartSpecificProps { export interface RadarChartSpecificProps { /** Show area fill @default true */ showArea?: boolean; + /** + * 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. + */ + max?: number | readonly number[]; } /** Props specific to heatmap charts */ From 5ac0c1f907dabd50519f2f16940d98380eda5422 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:04:29 +0000 Subject: [PATCH 060/151] fix(appkit-ui): radar shows an error for negative values and the empty state for zeros All-negative data gave a negative rim and a meaningless shape, and all zeros a rim of 0 and a dot. A radar with a negative value now renders an error state (and console.error) saying to shift or normalise the metrics or use a BarChart; one whose values are all 0 or missing shows "No data". Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/radar.test.tsx | 31 +++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 43 +++++++++++++++++-- 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx index 446bed6fc..5d883d8ee 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -59,3 +59,34 @@ describe("rim value (RAD-02)", () => { expect(opt.radar.indicator.map((i) => i.max)).toEqual([10, 5]); }); }); + +describe("values a radar can't draw (RAD-04)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index d4e0fcd63..a1c3404ba 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -199,6 +199,35 @@ function pieIsEmpty(normalized: { 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), + ); +} + /** Colors in the categorical palette before they repeat. */ const MAX_DISTINCT_COLORS = 8; @@ -487,6 +516,7 @@ export function BaseChart({ // 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 ?? @@ -494,12 +524,17 @@ export function BaseChart({ ? scatterXError(normalized) : isPieChart && "yDataMap" in normalized ? pieValueError(normalized) - : null), - [keyError, chartType, isPieChart, normalized], + : isRadarChart && "yDataMap" in normalized + ? radarValueError(normalized) + : null), + [keyError, chartType, isPieChart, isRadarChart, normalized], ); - // All-zero pies used to draw a full ring of equal "0%" slices. + // All-zero pies used to draw a full ring of equal "0%" slices, and an + // all-zero radar a dot. const pieEmpty = - isPieChart && "yDataMap" in normalized && pieIsEmpty(normalized); + (isPieChart || isRadarChart) && + "yDataMap" in normalized && + (isPieChart ? pieIsEmpty(normalized) : allZero(normalized)); useEffect(() => { if (chartError) { console.error(`[appkit-ui] ${chartType} chart: ${chartError}`); From b7e931014d1ccc72940aaf4bff4f216d0fd6681e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:06:06 +0000 Subject: [PATCH 061/151] feat(appkit-ui): radar metrics prop for one-row-per-entity data The radar wanted one row per metric and one column per entity, the reverse of a SQL result; entity rows were accepted and drew the entities as spokes. New `metrics` prop on RadarChart: with one row per entity, the listed columns become spokes and each row a polygon named by xKey (or the first text column). Unknown metrics are reported like unknown keys, and a click returns the entity row. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/radar.test.tsx | 35 ++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 46 ++++++++++++++++--- packages/appkit-ui/src/react/charts/click.ts | 4 ++ .../src/react/charts/create-chart.tsx | 2 +- .../appkit-ui/src/react/charts/normalize.ts | 40 ++++++++++++++++ packages/appkit-ui/src/react/charts/types.ts | 7 +++ 6 files changed, 126 insertions(+), 8 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx index 5d883d8ee..74b965a12 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -90,3 +90,38 @@ describe("values a radar can't draw (RAD-04)", () => { expect(getByText("No data")).toBeTruthy(); }); }); + +describe("one row per entity (RAD-06)", () => { + 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"'); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index a1c3404ba..0ad8d8d53 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -35,6 +35,8 @@ import { chartSizeStyle } from "./constants"; import { normalizeChartData, normalizeHeatmapData, + pivotRadarEntities, + RADAR_METRIC_KEY, unknownKeysMessage, } from "./normalize"; import { @@ -360,6 +362,8 @@ export interface BaseChartProps { showValues?: boolean; /** Per-`yKey` series type and value axis (bar, line, area). */ series?: Record; + /** Radar: metric columns of one-row-per-entity data. */ + metrics?: readonly string[]; } // ============================================================================ @@ -371,10 +375,10 @@ export interface BaseChartProps { * Renders using ECharts for consistent output across both formats. */ export function BaseChart({ - data, + data: dataProp, chartType, - xKey, - yKey, + xKey: xKeyProp, + yKey: yKeyProp, xType, seriesKey, orientation: orientationProp, @@ -406,7 +410,19 @@ export function BaseChart({ zoom = false, showValues = false, series: seriesConfig, + metrics, }: 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; + const xKey = radarPivot ? RADAR_METRIC_KEY : xKeyProp; + const yKey = radarPivot ? radarPivot.entities : yKeyProp; const v3 = defaults === "v3"; // v3 pies and donuts carry name, value and share in the legend instead of // slice labels, which overlap and get cut. @@ -488,8 +504,21 @@ export function BaseChart({ // A key that is not in the rows would draw a flat zero series; report it. const keyError = useMemo( - () => unknownKeysMessage(data, { xKey, yKey, yAxisKey, seriesKey }), - [data, xKey, yKey, yAxisKey, seriesKey], + () => + radarPivot + ? unknownKeysMessage(dataProp, { xKey: xKeyProp, metrics }) + : unknownKeysMessage(data, { xKey, yKey, yAxisKey, seriesKey }), + [ + radarPivot, + dataProp, + xKeyProp, + metrics, + data, + xKey, + yKey, + yAxisKey, + seriesKey, + ], ); // Memoize data normalization @@ -751,9 +780,12 @@ export function BaseChart({ "cellRowIndex" in normalized ? (normalized.cellRowIndex as number[]) : undefined, - seriesLabels: normalized.yFields.map((f) => formatLabel(f)), + seriesLabels: radarPivot + ? radarPivot.entities + : normalized.yFields.map((f) => formatLabel(f)), + seriesRows: radarPivot?.entityRows, }), - [chartType, data, normalized], + [chartType, data, normalized, radarPivot], ); const clickContextRef = useRef(clickContext); clickContextRef.current = clickContext; diff --git a/packages/appkit-ui/src/react/charts/click.ts b/packages/appkit-ui/src/react/charts/click.ts index af8a64331..fcb20de26 100644 --- a/packages/appkit-ui/src/react/charts/click.ts +++ b/packages/appkit-ui/src/react/charts/click.ts @@ -18,6 +18,8 @@ export interface ClickContext { 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 { @@ -178,6 +180,8 @@ export function resolveClickDatum( } 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/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index 3cdeb731c..1ad1a777d 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -99,7 +99,7 @@ const CHART_PROPS: Record = { ]), pie: PIE_PROPS, donut: PIE_PROPS, - radar: allKeys()(["showArea", "max"]), + radar: allKeys()(["showArea", "max", "metrics"]), heatmap: allKeys()([ "yAxisKey", "min", diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 360e2fada..ec0298340 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -429,6 +429,46 @@ function pivotLongRows( return { rows: Array.from(byX.values()), seriesNames }; } +/** 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"; diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 28b8040ca..41eb2b487 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -427,6 +427,13 @@ export interface RadarChartSpecificProps { * one per metric in row order. Unset: the data's largest value rounded up. */ max?: number | readonly number[]; + /** + * 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. + */ + metrics?: readonly string[]; } /** Props specific to heatmap charts */ From 1a5463c891d623bc1ddf95a162715005b2187565 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:06:59 +0000 Subject: [PATCH 062/151] fix(appkit-ui): radar truncates spoke names and sizes the radius to the space left Metric names were clipped at narrow widths with no truncation (4 of 6 at 280 px), and the polygon used about half of the box. With a measured size, spoke names now get up to a quarter of the width and are truncated with an ellipsis past it, and the radius is the space left after the names, the legend and the title. Before the first measurement the ECharts default radius is kept. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/radar.test.tsx | 28 ++++++++++++ .../appkit-ui/src/react/charts/options.ts | 44 ++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx index 74b965a12..f34ccaa68 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -125,3 +125,31 @@ describe("one row per entity (RAD-06)", () => { expect(getByRole("alert").textContent).toContain('metrics "power"'); }); }); + +describe("narrow radar (RAD-08)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index eccf9b305..19812c323 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -233,6 +233,48 @@ function radarAxisMaxima(ctx: OptionBuilderContext): number[] { return perAxis.map(() => shared); } +/** 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), + center: [ + "50%", + Math.round(titleBand + (height - legendBand - titleBand) / 2), + ], + axisName: { + color: ui.axisTitle, + width: nameWidth, + overflow: "truncate", + }, + }; +} + export function buildRadarOption( ctx: OptionBuilderContext, showArea = true, @@ -276,7 +318,7 @@ export function buildRadarOption( ...(i === 0 || !sharedScale ? { axisLabel: ringLabel } : {}), })), shape: "polygon", - axisName: { color: ui.axisTitle }, + ...radarLayout(ctx), axisLine: { lineStyle: { color: ui.grid } }, splitLine: { lineStyle: { color: ui.grid } }, }, From 011da60ff0091dd82c7ada9e1add10a2b93147fe Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:07:36 +0000 Subject: [PATCH 063/151] fix(appkit-ui): theme the radar ring bands In the dark theme the radar ring bands kept the ECharts light grey fill. The bands now alternate the theme grid color (at 35% opacity) with transparent, so they follow light and dark themes. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/radar.test.tsx | 25 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 5 ++++ 2 files changed, 30 insertions(+) diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx index f34ccaa68..2ebf8e743 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -153,3 +153,28 @@ describe("narrow radar (RAD-08)", () => { expect(opt.radar.radius).toBe(58); }); }); + +describe("dark theme (RAD-09)", () => { + 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"]); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 19812c323..9ff09718b 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -321,6 +321,11 @@ export function buildRadarOption( ...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: [ { From 1013e0c1f2cb1fde1c43fd4ffedb9b417edfc59d Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:09:02 +0000 Subject: [PATCH 064/151] fix(appkit-ui): heatmap sorts its axes and sums repeated cells Heatmap axes followed first appearance in the rows, so weekdays and hours came out shuffled, and repeated (x, y) rows were drawn on top of each other. Axes now put weekdays (Monday first) and month names in calendar order, numbers such as hours ascending and date strings chronologically; other text keeps row order. New `xOrder` and `yOrder` props override the order. Repeated cells are summed, with a console.warn. Columns taken by position without keys are handled in HM-02. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/heatmap.test.ts | 61 ++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 25 +++- .../src/react/charts/create-chart.tsx | 2 + .../appkit-ui/src/react/charts/normalize.ts | 109 ++++++++++++++++-- packages/appkit-ui/src/react/charts/types.ts | 8 ++ 5 files changed, 196 insertions(+), 9 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts 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..59497d5d5 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { normalizeHeatmapData } from "../normalize"; + +afterEach(() => vi.restoreAllMocks()); + +describe("heatmap axis order (C21)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 0ad8d8d53..da3a13e25 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -362,6 +362,9 @@ export interface BaseChartProps { showValues?: boolean; /** Per-`yKey` series type and value axis (bar, line, area). */ series?: Record; + /** Heatmap column and row order overrides. */ + xOrder?: readonly (string | number)[]; + yOrder?: readonly (string | number)[]; /** Radar: metric columns of one-row-per-entity data. */ metrics?: readonly string[]; } @@ -411,6 +414,8 @@ export function BaseChart({ showValues = false, series: seriesConfig, metrics, + xOrder, + yOrder, }: BaseChartProps) { // Radar with `metrics`: rows are entities; pivot to one row per metric. const radarPivot = useMemo( @@ -525,7 +530,11 @@ export function BaseChart({ const normalized = useMemo( () => chartType === "heatmap" - ? normalizeHeatmapData(data, xKey, yAxisKey, yKey, { keepNulls: v3 }) + ? 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. @@ -540,7 +549,19 @@ export function BaseChart({ keepNulls: v3 || chartType === "scatter", seriesKey, }), - [data, xKey, yKey, yAxisKey, orientation, chartType, xType, v3, seriesKey], + [ + data, + xKey, + yKey, + yAxisKey, + orientation, + chartType, + xType, + v3, + seriesKey, + xOrder, + yOrder, + ], ); // Data a chart can't draw is reported instead of drawing an empty plot. diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index 1ad1a777d..13297e9f0 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -105,6 +105,8 @@ const CHART_PROPS: Record = { "min", "max", "showLabels", + "xOrder", + "yOrder", ]), }; diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index ec0298340..d95efe8be 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -429,6 +429,77 @@ function pivotLongRows( 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; +} + /** Column that names the spokes of a radar pivoted from entity rows. */ export const RADAR_METRIC_KEY = "\u0000metric"; @@ -700,7 +771,11 @@ export function normalizeHeatmapData( xKey?: string, yAxisKey?: string, valueKey?: string | string[], - opts: { keepNulls?: boolean } = {}, + opts: { + keepNulls?: boolean; + xOrder?: readonly (string | number)[]; + yOrder?: readonly (string | number)[]; + } = {}, ): NormalizedHeatmapData { // First, get the standard normalization const jsonData = isArrowTable(data) @@ -742,8 +817,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(); @@ -758,6 +833,8 @@ 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; @@ -785,10 +862,18 @@ export function normalizeHeatmapData( } if (xIdx !== undefined && yIdx !== undefined) { - heatmapData.push([xIdx, yIdx, numValue]); - cellRowIndex.push(rowIdx); - 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); + } } } @@ -798,6 +883,16 @@ export function normalizeHeatmapData( ); } + 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; diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 41eb2b487..7ec6d4f1d 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -449,6 +449,14 @@ export interface HeatmapChartSpecificProps { max?: number; /** Show value labels on cells @default false */ showLabels?: boolean; + /** + * Column order: these values first, in this order. Unset: weekdays and + * months in calendar order, numbers ascending, dates chronologically, + * other text in row order. + */ + xOrder?: readonly (string | number)[]; + /** Row order, as {@link HeatmapChartSpecificProps.xOrder}. */ + yOrder?: readonly (string | number)[]; } // ============================================================================ From 7b5ea1c485ce6a9f1b77498f5549121655fb6605 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:10:27 +0000 Subject: [PATCH 065/151] fix(appkit-ui): heatmap labels cells only when the labels fit showLabels was on by default (the type said off) and past about ten columns the labels printed over each other. Unset, heatmap labels are now on for up to 100 cells when each cell is at least 32 px wide (measured), or at most 12 columns before the chart is measured; `showLabels` still forces them on or off. The type doc states the rule. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/heatmap.test.ts | 27 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 3 ++- .../appkit-ui/src/react/charts/options.ts | 27 ++++++++++++++++--- packages/appkit-ui/src/react/charts/types.ts | 5 +++- 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts index 59497d5d5..b29d48ae5 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import { normalizeHeatmapData } from "../normalize"; +import { buildHeatmapOption } from "../options"; afterEach(() => vi.restoreAllMocks()); @@ -59,3 +60,29 @@ describe("heatmap axis order (C21)", () => { expect(warn).toHaveBeenCalled(); }); }); + +describe("heatmap labels (HM-01)", () => { + 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, + ); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index da3a13e25..29a73e888 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -704,7 +704,8 @@ export function BaseChart({ heatmapData: heatmapNorm.heatmapData, min: min ?? heatmapNorm.min, max: typeof max === "number" ? max : heatmapNorm.max, - showLabels, + // Unset: labels when they fit the cells. + showLabels: showLabelsProp, }); } else if (isRadar) { opt = buildRadarOption(baseCtx, showArea, max); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 9ff09718b..44827b849 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -742,8 +742,29 @@ 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; +} + +/** 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( @@ -817,7 +838,7 @@ export function buildHeatmapOption( ...(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]), }, diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 7ec6d4f1d..80ee5fea8 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -447,7 +447,10 @@ export interface HeatmapChartSpecificProps { min?: number; /** Max value for color scale (auto-detected if not provided) */ max?: number; - /** Show value labels on cells @default false */ + /** + * Show value labels on cells. Unset: on for up to 100 cells when each cell + * is wide enough for a label. + */ showLabels?: boolean; /** * Column order: these values first, in this order. Unset: weekdays and From 89e2cf92f8b0e1a8cb7b3f03dccfc043f2c9d3e9 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:12:11 +0000 Subject: [PATCH 066/151] feat(appkit-ui): validate heatmap keys; columnKey, rowKey and valueKey aliases Wrong heatmap key combinations were silent: yKey used as the row dimension with no yAxisKey gave an all-zero grid, a mistyped yAxisKey collapsed every row into one, and keys not given were taken by column position. A value column that holds only text now renders an error state that explains the three roles; unknown keys are reported (C3) under the name the caller used; keys not given are picked from the free columns (the value from the numeric ones). New aliases on HeatmapChart: columnKey (xKey), rowKey (yAxisKey) and valueKey (yKey); the old names keep working. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../charts/__tests__/heatmap-keys.test.tsx | 67 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 29 ++++++-- .../src/react/charts/create-chart.tsx | 3 + .../appkit-ui/src/react/charts/normalize.ts | 30 ++++++--- packages/appkit-ui/src/react/charts/types.ts | 6 ++ 5 files changed, 122 insertions(+), 13 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx 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..dc455253f --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx @@ -0,0 +1,67 @@ +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 (HM-02)", () => { + 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"); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 29a73e888..7c8bfd3bf 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -362,6 +362,10 @@ export interface BaseChartProps { 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)[]; @@ -400,7 +404,10 @@ export function BaseChart({ showLabels: showLabelsProp, labelPosition = "outside", centerLabel, - yAxisKey, + yAxisKey: yAxisKeyProp, + columnKey, + rowKey, + valueKey, min, max, options: customOptions, @@ -426,8 +433,10 @@ export function BaseChart({ [chartType, dataProp, xKeyProp, metrics], ); const data = radarPivot?.rows ?? dataProp; - const xKey = radarPivot ? RADAR_METRIC_KEY : xKeyProp; - const yKey = radarPivot ? radarPivot.entities : yKeyProp; + // 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"; // v3 pies and donuts carry name, value and share in the legend instead of // slice labels, which overlap and get cut. @@ -512,7 +521,12 @@ export function BaseChart({ () => radarPivot ? unknownKeysMessage(dataProp, { xKey: xKeyProp, metrics }) - : unknownKeysMessage(data, { xKey, yKey, yAxisKey, seriesKey }), + : unknownKeysMessage(data, { + [columnKey ? "columnKey" : "xKey"]: xKey, + [valueKey ? "valueKey" : "yKey"]: yKey, + [rowKey ? "rowKey" : "yAxisKey"]: yAxisKey, + seriesKey, + }), [ radarPivot, dataProp, @@ -523,6 +537,9 @@ export function BaseChart({ yKey, yAxisKey, seriesKey, + columnKey, + rowKey, + valueKey, ], ); @@ -576,7 +593,9 @@ export function BaseChart({ ? pieValueError(normalized) : isRadarChart && "yDataMap" in normalized ? radarValueError(normalized) - : null), + : "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 diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index 13297e9f0..a34670959 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -107,6 +107,9 @@ const CHART_PROPS: Record = { "showLabels", "xOrder", "yOrder", + "columnKey", + "rowKey", + "valueKey", ]), }; diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index d95efe8be..d445497c4 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -751,6 +751,10 @@ export interface NormalizedHeatmapData extends NormalizedChartDataBase { 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 */ @@ -797,14 +801,21 @@ export function normalizeHeatmapData( } // 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(); @@ -877,7 +888,8 @@ export function normalizeHeatmapData( } } - if (nonNumeric.length > 0) { + 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])}).`, ); @@ -909,6 +921,8 @@ export function normalizeHeatmapData( cellRowIndex, min, max, + ...(valueIsText ? { valueIsText } : {}), + yAxisField: resolvedYAxisKey, }; } diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 80ee5fea8..f9f54988a 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -460,6 +460,12 @@ export interface HeatmapChartSpecificProps { xOrder?: readonly (string | number)[]; /** Row order, as {@link HeatmapChartSpecificProps.xOrder}. */ yOrder?: readonly (string | number)[]; + /** The column dimension; same as `xKey`. */ + columnKey?: string; + /** The row dimension; same as `yAxisKey`. */ + rowKey?: string; + /** The numeric cell value; same as `yKey`. */ + valueKey?: string; } // ============================================================================ From a19231d8cd798243f6792fe2742bbaa6c73bf8ee Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:12:49 +0000 Subject: [PATCH 067/151] fix(appkit-ui): centre the diverging heatmap scale on zero colorPalette="diverging" used the data range as is, so with data from -40 to +10 the zero cell took a red color. When the data has both signs and no min or max is given, the scale is widened to be symmetric around 0 (-40 to 40 here), so the middle color means zero. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../charts/__tests__/heatmap-keys.test.tsx | 25 ++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 34 +++++++++++++++++-- 2 files changed, 57 insertions(+), 2 deletions(-) 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 index dc455253f..7f46070f6 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx @@ -65,3 +65,28 @@ describe("heatmap keys (HM-02)", () => { expect(norm.xField).toBe("day"); }); }); + +describe("diverging heatmap (HM-04)", () => { + 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 }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 7c8bfd3bf..540028d14 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -230,6 +230,31 @@ function allZero(normalized: { ); } +/** + * 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 }; + } + return { min: min ?? dataMin, max: max ?? dataMax }; +} + /** Colors in the categorical palette before they repeat. */ const MAX_DISTINCT_COLORS = 8; @@ -721,8 +746,13 @@ export function BaseChart({ ...baseCtx, yAxisData: heatmapNorm.yAxisData, heatmapData: heatmapNorm.heatmapData, - min: min ?? heatmapNorm.min, - max: typeof max === "number" ? max : heatmapNorm.max, + ...heatmapScale( + heatmapNorm.min, + heatmapNorm.max, + min, + typeof max === "number" ? max : undefined, + resolvedPalette, + ), // Unset: labels when they fit the cells. showLabels: showLabelsProp, }); From a369f133ce04641fcd83b677641970e29cb67a8a Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:13:57 +0000 Subject: [PATCH 068/151] fix(appkit-ui): reserve room for the heatmap color scale; showLegend hides it The color scale sat at 2% from the right over a grid with fixed 15% margins, so its labels overlapped the cells (at 260 px it covered the last columns), showLegend={false} did not hide it, and its drag handles filtered cells. The grid now uses pixel margins with containLabel and a right margin sized to the scale bar and its widest end label; showLegend={false} hides the scale (colors still apply); drag handles are off. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/heatmap.test.ts | 35 +++++++++++++++++++ .../appkit-ui/src/react/charts/options.ts | 34 ++++++++++++++---- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts index b29d48ae5..523273959 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap.test.ts @@ -86,3 +86,38 @@ describe("heatmap labels (HM-01)", () => { ); }); }); + +describe("heatmap color scale (HM-05)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 44827b849..7617442c8 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -746,6 +746,11 @@ export interface HeatmapContext extends OptionBuilderContext { 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. */ @@ -776,6 +781,16 @@ export function buildHeatmapOption( 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: { @@ -791,10 +806,13 @@ 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", @@ -816,10 +834,14 @@ export function buildHeatmapOption( 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 }, formatter: axisFormatter && valueField From a901ceb55f3757233941c83e5b62f9b0893e39b8 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:15:45 +0000 Subject: [PATCH 069/151] feat(appkit-ui): sparkline prop on LineChart and AreaChart The KPI sparkline recipe (a LineChart at height 48 with an options override) misled in three cases: a null day drew a cliff to 0, one point drew nothing, and without the override the axis labels overlapped. New `sparkline` prop on LineChart and AreaChart: no axes, legend, title or margins, a y range fitted to the data, missing values kept as gaps (with or without v3), a dot for a single point (X5), and a 48 px default height. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/sparkline.test.tsx | 78 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 33 +++++++- .../src/react/charts/create-chart.tsx | 9 ++- packages/appkit-ui/src/react/charts/types.ts | 12 +++ 4 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/sparkline.test.tsx 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..4413cb79e --- /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 (LINE-06)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 540028d14..86ecff9eb 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -255,6 +255,28 @@ function heatmapScale( return { min: min ?? dataMin, max: max ?? dataMax }; } +/** + * 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; @@ -394,6 +416,8 @@ export interface BaseChartProps { /** 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[]; } @@ -446,6 +470,7 @@ export function BaseChart({ showValues = false, series: seriesConfig, metrics, + sparkline: sparklineProp = false, xOrder, yOrder, }: BaseChartProps) { @@ -463,6 +488,8 @@ export function BaseChart({ 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 = @@ -588,7 +615,8 @@ export function BaseChart({ ? "category" : undefined), // Scatter drops points with a missing value instead of plotting 0. - keepNulls: v3 || chartType === "scatter", + // Sparklines leave a gap at a missing day instead of a cliff to 0. + keepNulls: v3 || sparkline || chartType === "scatter", seriesKey, }), [ @@ -603,6 +631,7 @@ export function BaseChart({ seriesKey, xOrder, yOrder, + sparkline, ], ); @@ -785,6 +814,7 @@ export function BaseChart({ } // Apply selection after custom options; empty selection is a no-op. + if (sparkline) opt = toSparkline(opt); const merged = mergeChartOptions(opt, customOptions); return applySelectionEmphasis(merged, selected); }, [ @@ -818,6 +848,7 @@ export function BaseChart({ zoom, showValues, seriesConfig, + sparkline, ]); // Heatmap data uses axis indexes; preserve labels for click results instead diff --git a/packages/appkit-ui/src/react/charts/create-chart.tsx b/packages/appkit-ui/src/react/charts/create-chart.tsx index a34670959..abf8b27db 100644 --- a/packages/appkit-ui/src/react/charts/create-chart.tsx +++ b/packages/appkit-ui/src/react/charts/create-chart.tsx @@ -74,6 +74,7 @@ const CHART_PROPS: Record = { "series", ]), line: allKeys()([ + "sparkline", "referenceLines", "zoom", "series", @@ -83,6 +84,7 @@ const CHART_PROPS: Record = { "connectNulls", ]), area: allKeys()([ + "sparkline", "referenceLines", "zoom", "series", @@ -205,7 +207,7 @@ export function createChart( loading, error, // Common props - height, + height: heightProp, className, ariaLabel, testId, @@ -227,6 +229,11 @@ export function createChart( 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( diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index f9f54988a..5e755115b 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -360,6 +360,12 @@ export interface BarChartSpecificProps /** Props specific to line charts */ export interface LineChartSpecificProps extends ReferenceLineProps, ZoomProps, ComboProps { + /** + * 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. + */ + sparkline?: boolean; /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ @@ -376,6 +382,12 @@ export interface LineChartSpecificProps /** Props specific to area charts */ export interface AreaChartSpecificProps extends ReferenceLineProps, ZoomProps, ComboProps { + /** + * 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. + */ + sparkline?: boolean; /** Size of the data point symbols @default 8 */ symbolSize?: number; /** Show data point symbols @default false */ From 48073ca34ac77df98dc189ae874e5bf9a2da04ca Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:18:31 +0000 Subject: [PATCH 070/151] fix(appkit-ui): infer a bar first and a table above 50 categories in Genie result charts Genie result charts chose a pie for up to seven categories and a line on a nominal (text) axis above 100. Text categories with a measure now always infer a bar chart; above 50 categories no chart is inferred and the result stays a table. Pie and donut are still offered as alternatives for up to 5 categories with no negative values; line and area are no longer offered on a text axis, since a line implies an order the categories do not have. Tests updated to the new rules. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../__tests__/genie-chart-inference.test.ts | 60 +++++++------------ .../src/react/genie/genie-chart-inference.ts | 57 ++++++------------ 2 files changed, 39 insertions(+), 78 deletions(-) diff --git a/packages/appkit-ui/src/react/genie/__tests__/genie-chart-inference.test.ts b/packages/appkit-ui/src/react/genie/__tests__/genie-chart-inference.test.ts index 75453fa99..46716d4ac 100644 --- a/packages/appkit-ui/src/react/genie/__tests__/genie-chart-inference.test.ts +++ b/packages/appkit-ui/src/react/genie/__tests__/genie-chart-inference.test.ts @@ -108,11 +108,11 @@ describe("inferChartType — Rule 1: timeseries", () => { }); // --------------------------------------------------------------------------- -// Rule 2: STRING + 1 numeric, ≤7 categories → pie +// Rule 2: STRING + 1 numeric, few categories → bar, never pie (C30) // --------------------------------------------------------------------------- -describe("inferChartType — Rule 2: pie", () => { - test("string + 1 numeric, 3 categories → pie", () => { +describe("inferChartType — Rule 2: few categories → bar", () => { + test("string + 1 numeric, 3 categories → bar", () => { const columns = cols(["region", "string"], ["sales", "numeric"]); const rows = makeRows( ["region", "sales"], @@ -124,25 +124,25 @@ describe("inferChartType — Rule 2: pie", () => { ); const result = inferChartType(rows, columns); expect(result).toEqual({ - chartType: "pie", + chartType: "bar", xKey: "region", yKey: "sales", }); }); - test("string + 1 numeric, exactly 7 categories → pie", () => { + test("string + 1 numeric, exactly 7 categories → bar", () => { const columns = cols(["cat", "string"], ["val", "numeric"]); const rows = makeRows( ["cat", "val"], Array.from({ length: 7 }, (_, i) => [`cat${i}`, i * 10]), ); const result = inferChartType(rows, columns); - expect(result?.chartType).toBe("pie"); + expect(result?.chartType).toBe("bar"); }); }); // --------------------------------------------------------------------------- -// Rule 3: STRING + 1 numeric, ≤100 categories → bar +// Rule 3: STRING + 1 numeric, ≤50 categories → bar // --------------------------------------------------------------------------- describe("inferChartType — Rule 3: bar", () => { @@ -172,22 +172,17 @@ describe("inferChartType — Rule 3: bar", () => { }); // --------------------------------------------------------------------------- -// Rule 4: STRING + 1 numeric, >100 categories → line +// STRING + 1 numeric, >50 categories → no chart (a table) // --------------------------------------------------------------------------- -describe("inferChartType — Rule 4: many categories → line", () => { - test("string + 1 numeric, 150 categories → line", () => { +describe("inferChartType — many categories → table", () => { + test("string + 1 numeric, 150 categories → null", () => { const columns = cols(["city", "string"], ["population", "numeric"]); const rows = makeRows( ["city", "population"], Array.from({ length: 150 }, (_, i) => [`city${i}`, i * 1000]), ); - const result = inferChartType(rows, columns); - expect(result).toEqual({ - chartType: "line", - xKey: "city", - yKey: "population", - }); + expect(inferChartType(rows, columns)).toBeNull(); }); }); @@ -216,11 +211,11 @@ describe("inferChartType — Rule 5: grouped bar", () => { }); // --------------------------------------------------------------------------- -// Rule 6: STRING + N numerics, >50 categories → line +// STRING + N numerics, >50 categories → no chart (a table) // --------------------------------------------------------------------------- -describe("inferChartType — Rule 6: multi-series line", () => { - test("string + 2 numerics, 60 categories → line", () => { +describe("inferChartType — many categories, several measures → table", () => { + test("string + 2 numerics, 60 categories → null", () => { const columns = cols( ["item", "string"], ["metric_a", "numeric"], @@ -230,12 +225,7 @@ describe("inferChartType — Rule 6: multi-series line", () => { ["item", "metric_a", "metric_b"], Array.from({ length: 60 }, (_, i) => [`item${i}`, i, i * 2]), ); - const result = inferChartType(rows, columns); - expect(result).toEqual({ - chartType: "line", - xKey: "item", - yKey: ["metric_a", "metric_b"], - }); + expect(inferChartType(rows, columns)).toBeNull(); }); }); @@ -357,28 +347,22 @@ describe("getCompatibleChartTypes", () => { ], ); expect(getCompatibleChartTypes(rows, columns)).toEqual([ + "bar", "pie", "donut", - "bar", - "line", - "area", ]); }); - test("string + 1 numeric, many categories → bar, line, area (no pie)", () => { + test("string + 1 numeric, many categories → bar only", () => { const columns = cols(["product", "string"], ["revenue", "numeric"]); const rows = makeRows( ["product", "revenue"], Array.from({ length: 15 }, (_, i) => [`product${i}`, i * 100]), ); - expect(getCompatibleChartTypes(rows, columns)).toEqual([ - "bar", - "line", - "area", - ]); + expect(getCompatibleChartTypes(rows, columns)).toEqual(["bar"]); }); - test("string + N numerics → bar, line, area", () => { + test("string + N numerics → bar only", () => { const columns = cols( ["department", "string"], ["budget", "numeric"], @@ -388,11 +372,7 @@ describe("getCompatibleChartTypes", () => { ["department", "budget", "actual"], Array.from({ length: 8 }, (_, i) => [`dept${i}`, i * 100, i * 90]), ); - expect(getCompatibleChartTypes(rows, columns)).toEqual([ - "bar", - "line", - "area", - ]); + expect(getCompatibleChartTypes(rows, columns)).toEqual(["bar"]); }); test("2+ numerics only → scatter, line, area", () => { diff --git a/packages/appkit-ui/src/react/genie/genie-chart-inference.ts b/packages/appkit-ui/src/react/genie/genie-chart-inference.ts index 5a8e954d4..78039f71a 100644 --- a/packages/appkit-ui/src/react/genie/genie-chart-inference.ts +++ b/packages/appkit-ui/src/react/genie/genie-chart-inference.ts @@ -43,12 +43,10 @@ import type { GenieColumnMeta } from "./genie-query-transform"; const INFERENCE_CONFIG = { /** Min rows required to show any chart */ minRows: 2, - /** Max unique categories for pie chart */ - pieMaxCategories: 7, - /** Max unique categories for bar chart (single series) */ - barMaxCategories: 100, - /** Max unique categories for grouped bar chart (multi series) */ - groupedBarMaxCategories: 50, + /** Max unique categories for which pie/donut are offered (never inferred) */ + pieMaxCategories: 5, + /** Max unique categories for a bar chart; past it the result stays a table */ + barMaxCategories: 50, } as const; export interface ChartInference { @@ -127,38 +125,21 @@ export function inferChartType( }; } - // Rules 2–6: STRING + numeric(s) + // Rules 2–3: STRING + numeric(s). Categories are compared by length, which + // a bar shows best; a pie (Rule 2 used to pick one for up to 7 categories) + // is only offered as an alternative. Past 50 categories no chart is + // inferred and the result stays a table (a line on a nominal axis, the old + // rule above 100, implies an order the categories don't have). if (stringCols.length > 0 && numericCols.length >= 1) { const xKey = stringCols[0].name; - const uniqueCategories = countUnique(rows, xKey); - - if (numericCols.length === 1) { - const yKey = numericCols[0].name; - - // Rule 2: few categories → pie (skip if negative values) - if ( - uniqueCategories <= INFERENCE_CONFIG.pieMaxCategories && - !hasNegativeValues(rows, yKey) - ) { - return { chartType: "pie", xKey, yKey }; - } - // Rule 3: moderate categories → bar - if (uniqueCategories <= INFERENCE_CONFIG.barMaxCategories) { - return { chartType: "bar", xKey, yKey }; - } - // Rule 4: many categories → line - return { chartType: "line", xKey, yKey }; - } - - // Multiple numerics - const yKey = numericCols.map((c) => c.name); - - // Rule 5: moderate categories → bar (grouped) - if (uniqueCategories <= INFERENCE_CONFIG.groupedBarMaxCategories) { - return { chartType: "bar", xKey, yKey }; + if (countUnique(rows, xKey) > INFERENCE_CONFIG.barMaxCategories) { + return null; } - // Rule 6: many categories → line (multi-series) - return { chartType: "line", xKey, yKey }; + const yKey = + numericCols.length === 1 + ? numericCols[0].name + : numericCols.map((c) => c.name); + return { chartType: "bar", xKey, yKey }; } // Rule 7: 2+ numerics only (no string, no date) → scatter @@ -208,13 +189,13 @@ export function getCompatibleChartTypes( uniqueCategories <= INFERENCE_CONFIG.pieMaxCategories && !hasNegativeValues(rows, yKey) ) { - return ["pie", "donut", "bar", "line", "area"]; + return ["bar", "pie", "donut"]; } - return ["bar", "line", "area"]; + return ["bar"]; } // Multiple numerics - return ["bar", "line", "area"]; + return ["bar"]; } // 2+ numerics only → scatter-compatible From f509a44ad5f86dd06aea7f6a4ede847675146dc3 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:22:32 +0000 Subject: [PATCH 071/151] fix(appkit-ui): label null and empty categories; stacked bar tooltip total Bar P2 items from the second pass: (1) null and empty-string categories both became "", so two different rows got two blank labels and a click returned name "". Missing categories are now labelled "(null)" and empty ones "(empty)" (Arrow nulls used to become 0). (2) Stacked bar tooltips list every series, top band first on vertical bars, and end with the total. (3) The stale label margin after an orientation change was fixed by C5 (notMerge); a test now covers it. Not done: a per-series color for negative values (negativeColor). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/charts/__tests__/normalize.test.ts | 4 +- .../src/react/charts/__tests__/p2.test.tsx | 98 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 3 +- .../appkit-ui/src/react/charts/normalize.ts | 22 ++++- .../appkit-ui/src/react/charts/options.ts | 46 +++++++++ 5 files changed, 168 insertions(+), 5 deletions(-) create mode 100644 packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx 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 a8e89e7f5..cbc32fadf 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts +++ b/packages/appkit-ui/src/react/charts/__tests__/normalize.test.ts @@ -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"); }); 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..2dc531508 --- /dev/null +++ b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx @@ -0,0 +1,98 @@ +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 P2 (BAR-P2)", () => { + 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 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 (C5)", 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); + }); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 86ecff9eb..fdd7d5e3e 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -35,6 +35,7 @@ import { chartSizeStyle } from "./constants"; import { normalizeChartData, normalizeHeatmapData, + NULL_X_LABEL, pivotRadarEntities, RADAR_METRIC_KEY, unknownKeysMessage, @@ -143,7 +144,7 @@ function scatterXError(normalized: { xData: (string | number)[]; xField: string; }): string | null { - const values = normalized.xData.filter((x) => x !== ""); + const values = normalized.xData.filter((x) => x !== "" && x !== NULL_X_LABEL); if (values.length === 0) return null; const numeric = values.some( (x) => diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index d445497c4..5c220a6a1 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -18,6 +18,7 @@ import { sortNumericAscending, sortTimeSeriesAscending, toChartArray, + toChartValue, toChronologicalValue, } from "./utils"; @@ -245,7 +246,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; @@ -500,6 +501,20 @@ function orderHeatmapAxis( 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"; @@ -559,6 +574,9 @@ function sortByXAxis( 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), @@ -654,7 +672,7 @@ export function normalizeChartData( : inferXType(rawXData)); const chartType = xAxisType === "time" ? "timeseries" : "categorical"; - let xData = toChartArray(rawXData); + let xData = arrowXValues(rawXData); let yDataMap: Record = {}; for (const key of resolvedYKeys) { yDataMap[key] = toChartArray(rawYDataMap[key] ?? [], keepNulls); diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 7617442c8..3330fe25d 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -182,6 +182,45 @@ 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). + */ +function stackedTooltip(ctx: OptionBuilderContext, topFirst: boolean) { + 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); + if (value !== "" && Number.isFinite(n)) total += n; + const field = ctx.yFields[item.seriesIndex ?? 0]; + 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 ?? ""); + const totalLine = `Total: ${escapeHtml(format(total, ctx.yFields[0]))}`; + return [head, ...lines, totalLine].join("
"); + }; +} + function tooltipValueFormatter(formatter: ChartValueFormatter, field: string) { return (value: unknown) => formatter(toMeasureValue(value), field); } @@ -660,6 +699,9 @@ export function buildHorizontalBarOption( ...tooltipTokens(ui), trigger: "axis", axisPointer: { type: "shadow" }, + ...(stacked && hasMultipleSeries + ? { formatter: stackedTooltip(ctx, false) } + : {}), }, legend: ctx.showLegend && hasMultipleSeries @@ -1130,6 +1172,10 @@ export function buildCartesianOption( trigger: isScatter ? "item" : "axis", // Scatter: both measures, named, not just y. ...(isScatter ? { formatter: scatterTooltip(ctx, isTimeScatter) } : {}), + // Stacked bars: every series and the total, top band first. + ...(stacked && hasMultipleSeries && chartType === "bar" + ? { formatter: stackedTooltip(ctx, true) } + : {}), }, legend: ctx.showLegend && hasMultipleSeries From 7a9777377ad54ffd13aa4cf87114af8719a4baba Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:24:32 +0000 Subject: [PATCH 072/151] fix(appkit-ui): leave rows with an unparseable date off the time axis, sort the rest A row whose date could not be parsed ("TBD") lost its point, broke the line and stopped the whole series from being sorted, with no warning (and since C1 one such value turned the axis into categories). A stray non-date among at least three dates (up to 10% of the rows) now still gives a time axis; those rows are left off it with a console.warn, and the rest is sorted. Source-row indices follow, so clicks still map to the right rows. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/p2.test.tsx | 20 +++++++++++ .../appkit-ui/src/react/charts/normalize.ts | 35 +++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx index 2dc531508..d2f5cf096 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx @@ -96,3 +96,23 @@ describe("bar P2 (BAR-P2)", () => { }); }); }); + +describe("line P2 (LINE-P2)", () => { + 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(); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/normalize.ts b/packages/appkit-ui/src/react/charts/normalize.ts index 5c220a6a1..33258c636 100644 --- a/packages/appkit-ui/src/react/charts/normalize.ts +++ b/packages/appkit-ui/src/react/charts/normalize.ts @@ -70,13 +70,19 @@ function isMissing(value: unknown): boolean { * dates gives `"time"`, anything else `"category"`. Column names play no part. */ function inferXType(values: readonly unknown[]): XAxisType { - let present = 0; + let dates = 0; + let others = 0; for (const value of values) { if (isMissing(value)) continue; - present++; - if (!(value instanceof Date) && !isDateString(value)) return "category"; - } - return present > 0 ? "time" : "category"; + 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[] { @@ -584,7 +590,24 @@ function sortByXAxis( const fields = [...yFields, ROW_INDEX_KEY]; let sorted = { xData, yDataMap: tracked }; if (chartType === "timeseries") { - sorted = sortTimeSeriesAscending(xData, tracked, fields); + // 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 && From d7a40edc782ab862e9a632465ad677cc4813c001 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:25:44 +0000 Subject: [PATCH 073/151] fix(appkit-ui): stacked area tooltip with total; warn on mixed signs; fainter overlaps Area P2 items from the second pass: (1) the stacked tooltip listed the bottom band first and had no total; it now lists the top band first and ends with the total. (2) A stack that mixes positive and negative values (its bands cross) logs a console.warn. (3) Unstacked overlapping fills blended into a third color at 30% opacity; with several unstacked series the fill drops to 12% so the lines carry the series. Not done: a 100% stacked mode, and a stack-aware field for the axis tick formatter (it still gets the first yKey). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/p2.test.tsx | 49 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 26 ++++++++++ .../appkit-ui/src/react/charts/options.ts | 13 +++-- 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx index d2f5cf096..396235d2a 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx @@ -116,3 +116,52 @@ describe("line P2 (LINE-P2)", () => { expect(warn).toHaveBeenCalled(); }); }); + +describe("area P2 (AREA-P2)", () => { + 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); + }); +}); diff --git a/packages/appkit-ui/src/react/charts/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index fdd7d5e3e..a842adaad 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -682,6 +682,32 @@ export function BaseChart({ } }, [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]); + // 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; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 3330fe25d..7bf3a62ea 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -1172,8 +1172,10 @@ export function buildCartesianOption( trigger: isScatter ? "item" : "axis", // Scatter: both measures, named, not just y. ...(isScatter ? { formatter: scatterTooltip(ctx, isTimeScatter) } : {}), - // Stacked bars: every series and the total, top band first. - ...(stacked && hasMultipleSeries && chartType === "bar" + // Stacked bars and areas: every series and the total, top band first. + ...(stacked && + hasMultipleSeries && + (chartType === "bar" || chartType === "area") ? { formatter: stackedTooltip(ctx, true) } : {}), }, @@ -1300,7 +1302,12 @@ export function buildCartesianOption( // 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, - areaStyle: own === "area" ? { opacity: 0.3 } : 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") From e4a5dc44115ed1ea5884866eaa05675f52fd6da7 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:27:01 +0000 Subject: [PATCH 074/151] fix(appkit-ui): readable inside labels; no legend rescale; warn on duplicates, extra yKeys Pie P2 items from the second pass: (1) null and empty slice names are labelled "(null)" and "(empty)" (BAR-P2), and repeated names log a warning, since they share one legend entry. (2) Inside labels took the slice color and vanished; they are white with a dark outline. labelPosition="center" drew only the first slice label in the middle; it now shows the hovered slice. (3) A legend click hid a slice and rescaled the rest to a full circle; legend selection is off. (4) Only the first yKey is drawn; extra yKeys now log a warning. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/pie.test.tsx | 50 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 24 +++++++++ .../appkit-ui/src/react/charts/options.ts | 20 ++++++-- 3 files changed, 91 insertions(+), 3 deletions(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx index dfb53ff71..b6bf697f6 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/pie.test.tsx @@ -276,3 +276,53 @@ describe("donut hole text (PIE-07)", () => { ); }); }); + +describe("pie P2 (PIE-P2)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index a842adaad..590479db2 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -708,6 +708,30 @@ export function BaseChart({ } }, [mixedSignStack]); + // 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; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 7bf3a62ea..19781a258 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -652,6 +652,9 @@ export function buildPieOption( 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: [ @@ -663,14 +666,25 @@ export function buildPieOption( : `${PIE_OUTER_RADIUS}%`, center: layout.center, data: pieData, + // 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, + ...(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, From 9f689466a1e24342aafddfb406ffb5b8c6178d6f Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:28:06 +0000 Subject: [PATCH 075/151] fix(appkit-ui): draw scatter points at least 2 px; cover numeric-string x Scatter P2 items from the second pass: (1) symbolSize={0} drew nothing and 1 drew sub-pixel specks, with no warning; scatter points are now drawn at least 2 px and a smaller size logs a warning. (2) Numeric-string x stayed a string when the rows also held a date column; since C1 the axis type comes from xKey only, and a test now covers it. (3) The Arrow-table failure (SCAT-12) was fixed by X1. Not done: colorKey, sizeKey and labelKey (color-by, size-by and point labels from columns); showValues (C35) labels points with their value. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/p2.test.tsx | 37 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 8 ++++ .../appkit-ui/src/react/charts/options.ts | 10 ++++- 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx index 396235d2a..ad6aba268 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/p2.test.tsx @@ -165,3 +165,40 @@ describe("area P2 (AREA-P2)", () => { ).toBe(true); }); }); + +describe("scatter P2 (SCATTER-P2)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 590479db2..26cea3f5a 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -708,6 +708,14 @@ export function BaseChart({ } }, [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]); + // A pie shows one measure, and repeated slice names share a legend entry. const pieWarning = useMemo(() => { if (chartType !== "pie" && chartType !== "donut") return null; diff --git a/packages/appkit-ui/src/react/charts/options.ts b/packages/appkit-ui/src/react/charts/options.ts index 19781a258..08c604ded 100644 --- a/packages/appkit-ui/src/react/charts/options.ts +++ b/packages/appkit-ui/src/react/charts/options.ts @@ -979,6 +979,9 @@ function scatterTooltip(ctx: OptionBuilderContext, xIsTime = false) { }; } +/** 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; @@ -1312,7 +1315,12 @@ export function buildCartesianOption( // 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 || ownLineLike ? symbolSize : undefined, + // 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, From 4c293cfad4a58e96acd9a80cf1d90eb796ef7c2d Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:29:02 +0000 Subject: [PATCH 076/151] fix(appkit-ui): sequential ramp for categorical palettes; pad a zero-width scale Heatmap P2 items from the second pass: (1) colorPalette="categorical" was used as a continuous ramp of unrelated hues; heatmaps now use the sequential palette instead and log a warning. (2) min equal to max, or all-equal values, gave a degenerate scale; the range is widened by 1 each way so cells take the middle color. (3) The color scale can be hidden and its drag handles are off (HM-05), and click seriesName is the value column (X2). Not done: warning on custom colors with unrelated hues; middle-ellipsis de-duplication of truncated axis labels (C14 measures width). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../charts/__tests__/heatmap-keys.test.tsx | 38 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 23 ++++++++++- 2 files changed, 59 insertions(+), 2 deletions(-) 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 index 7f46070f6..7febf60b3 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/heatmap-keys.test.tsx @@ -90,3 +90,41 @@ describe("diverging heatmap (HM-04)", () => { expect(option.visualMap[0]).toMatchObject({ min: -40, max: 40 }); }); }); + +describe("heatmap P2 (HEATMAP-P2)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 26cea3f5a..2a9a48134 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -253,7 +253,12 @@ function heatmapScale( const extent = Math.max(Math.abs(dataMin), Math.abs(dataMax)); return { min: -extent, max: extent }; } - return { min: min ?? dataMin, max: max ?? dataMax }; + 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 }; } /** @@ -503,7 +508,13 @@ export function BaseChart({ // 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); // Theme tokens such as var(--chart-cat-1) are resolved before ECharts. const resolvedCustomColors = useResolvedColors(customColors); @@ -716,6 +727,14 @@ export function BaseChart({ } }, [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; From 02a0a77ab03639842747e0e8e89c1fb6785c87c9 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:30:16 +0000 Subject: [PATCH 077/151] fix(appkit-ui): radar polygons keep their color by series name Radar P2 items from the second pass: (1) a polygon color followed its index in yKey, so removing the first series recolored the others; each series name now keeps the palette slot it first got for the life of the chart. (2) The radius used half the box (RAD-13); with a measured size the radius now fills the space left by the names (RAD-08). (3) Props a radar ignores warn in development (X8). Not done: name-stable colors for the other chart types. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/charts/__tests__/radar.test.tsx | 36 +++++++++++++++++++ packages/appkit-ui/src/react/charts/base.tsx | 20 ++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx index 2ebf8e743..ae4db4da6 100644 --- a/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx +++ b/packages/appkit-ui/src/react/charts/__tests__/radar.test.tsx @@ -178,3 +178,39 @@ describe("dark theme (RAD-09)", () => { expect(opt.radar.splitArea.areaStyle.color).toEqual([grid, "transparent"]); }); }); + +describe("radar P2 (RADAR-P2)", () => { + 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/base.tsx b/packages/appkit-ui/src/react/charts/base.tsx index 2a9a48134..d538697db 100644 --- a/packages/appkit-ui/src/react/charts/base.tsx +++ b/packages/appkit-ui/src/react/charts/base.tsx @@ -520,6 +520,24 @@ export function BaseChart({ 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(); // Handler presence enables line interaction and gates events. Tracking the @@ -802,7 +820,7 @@ export function BaseChart({ xData, yDataMap, yFields, - colors, + colors: chartType === "radar" ? stableSeriesColors(yFields) : colors, title, showLegend, xField, From b6dfa163fbe526cb61f7cc494bbe4dd52bd1548c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:34:23 +0000 Subject: [PATCH 078/151] fix(appkit-ui): format DataTable cells by column type, never by name DataTable ran every cell that parsed as a number through the chart formatter: ids and years were abbreviated (10021 -> "10K"), "02134" became "2.1K", null/""/false/[] showed "0", and any key containing cost/price/spend/revenue/usd was shown as USD. Cells are now formatted by a column kind inferred from all of the column values (number, text, boolean, date, timestamp, json): numbers at full precision with separators above four digits, numeric text with a leading zero kept as text, booleans as true/false, timestamps as wall-clock text, objects as JSON, empty values as a dash. The name-based formatChartValue is removed (it had no other caller). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- packages/appkit-ui/src/react/lib/format.ts | 38 -------- .../react/table/__tests__/cell-format.test.ts | 44 +++++++++ .../appkit-ui/src/react/table/cell-format.ts | 93 +++++++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 8 +- .../src/react/table/table-wrapper.tsx | 29 +++--- 5 files changed, 156 insertions(+), 56 deletions(-) create mode 100644 packages/appkit-ui/src/react/table/__tests__/cell-format.test.ts create mode 100644 packages/appkit-ui/src/react/table/cell-format.ts diff --git a/packages/appkit-ui/src/react/lib/format.ts b/packages/appkit-ui/src/react/lib/format.ts index a87f5901d..fbeadbfc9 100644 --- a/packages/appkit-ui/src/react/lib/format.ts +++ b/packages/appkit-ui/src/react/lib/format.ts @@ -1,43 +1,5 @@ import { formatLabel } from "../../js/format"; -/** - * Formats numeric values based on field name context - * @param value - The numeric value to format - * @param fieldName - The field name to determine formatting - * @returns Formatted string representation - * @example - * formatChartValue(1234.56, "cost") // "$1,234.56" - * formatChartValue(5000, "users") // "5.0k" - * formatChartValue(42.7, "percentage") // "42.7" - */ -export function formatChartValue(value: number, fieldName: string): string { - if ( - fieldName.toLowerCase().includes("cost") || - fieldName.toLowerCase().includes("price") || - fieldName.toLowerCase().includes("spend") || - fieldName.toLowerCase().includes("revenue") || - fieldName.toLowerCase().includes("usd") - ) { - return new Intl.NumberFormat("en-US", { - style: "currency", - currency: "USD", - minimumFractionDigits: 2, - maximumFractionDigits: 2, - }).format(value); - } - - if (value >= 1000) { - return new Intl.NumberFormat("en-US", { - notation: "compact", - maximumFractionDigits: 1, - }).format(value); - } - - return value.toLocaleString("en-US", { - maximumFractionDigits: 2, - }); -} - /** * Converts field names to human-readable labels * @param field - Field name in camelCase or snake_case diff --git a/packages/appkit-ui/src/react/table/__tests__/cell-format.test.ts b/packages/appkit-ui/src/react/table/__tests__/cell-format.test.ts new file mode 100644 index 000000000..7b9b388b3 --- /dev/null +++ b/packages/appkit-ui/src/react/table/__tests__/cell-format.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, test } from "vitest"; + +import { EMPTY_CELL, formatCell, inferColumnKind } from "../cell-format"; + +describe("inferColumnKind", () => { + test.each([ + [[1, 2, null], "number"], + [["12.50", "3"], "number"], + [["02134", "10021"], "text"], + [[true, false], "boolean"], + [["2026-01-01", "2026-01-02"], "date"], + [["2026-01-01 10:00:00", "2026-01-01"], "timestamp"], + [[{ a: 1 }], "json"], + [[1, "abc"], "text"], + [[null, ""], "text"], + ])("%j is %s", (values, kind) => { + expect(inferColumnKind(values)).toBe(kind); + }); +}); + +describe("formatCell", () => { + test("numbers keep full precision and are never abbreviated", () => { + expect(formatCell(10021, "number")).toBe("10,021"); + expect(formatCell(2024, "number")).toBe("2024"); + expect(formatCell("15234567.891", "number")).toBe("15,234,567.891"); + expect(formatCell(-12.5, "number")).toBe("-12.5"); + }); + + test("empty values are a dash, not 0", () => { + expect(formatCell(null, "number")).toBe(EMPTY_CELL); + expect(formatCell(undefined, "text")).toBe(EMPTY_CELL); + expect(formatCell("", "number")).toBe(EMPTY_CELL); + }); + + test("other kinds", () => { + expect(formatCell(false, "boolean")).toBe("false"); + expect(formatCell([], "json")).toBe("[]"); + expect(formatCell({ a: 1 }, "json")).toBe('{"a":1}'); + expect(formatCell("2026-01-01T10:00:00.000Z", "timestamp")).toBe( + "2026-01-01 10:00:00 UTC", + ); + expect(formatCell("02134", "text")).toBe("02134"); + }); +}); diff --git a/packages/appkit-ui/src/react/table/cell-format.ts b/packages/appkit-ui/src/react/table/cell-format.ts new file mode 100644 index 000000000..382c63514 --- /dev/null +++ b/packages/appkit-ui/src/react/table/cell-format.ts @@ -0,0 +1,93 @@ +/** How a DataTable column's cells are shown. Inferred from the values, never from the key. */ +type ColumnKind = "number" | "text" | "boolean" | "date" | "timestamp" | "json"; + +/** Shown for null, undefined and empty-string cells. */ +export const EMPTY_CELL = "—"; + +// A number written as text: optional sign, no leading zero (so "02134" stays a +// code), optional fraction. DECIMAL and BIGINT values arrive in this form. +const NUMERIC_TEXT = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/; +const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; +const TIMESTAMP = + /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(:\d{2})?(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/; + +function isEmpty(value: unknown): boolean { + return value === null || value === undefined || value === ""; +} + +function kindOf(value: unknown): ColumnKind { + if (typeof value === "number" || typeof value === "bigint") return "number"; + if (typeof value === "boolean") return "boolean"; + if (value instanceof Date) return "timestamp"; + if (typeof value === "object") return "json"; + const text = String(value); + if (NUMERIC_TEXT.test(text)) return "number"; + if (DATE_ONLY.test(text)) return "date"; + if (TIMESTAMP.test(text)) return "timestamp"; + return "text"; +} + +/** + * Infers a column's kind from all of its non-empty values. Mixed columns are + * text, so one odd value never reformats the rest. + */ +export function inferColumnKind(values: readonly unknown[]): ColumnKind { + let kind: ColumnKind | null = null; + for (const value of values) { + if (isEmpty(value)) continue; + const next = kindOf(value); + if (kind === null) kind = next; + else if (kind !== next) { + if ( + (kind === "date" && next === "timestamp") || + (kind === "timestamp" && next === "date") + ) { + kind = "timestamp"; + continue; + } + return "text"; + } + } + return kind ?? "text"; +} + +function formatNumber(value: unknown): string { + const text = typeof value === "string" ? value : String(value); + const [whole, fraction] = text.replace(/^-/, "").split("."); + // Four-digit integers (years, small counts) read better without a separator. + const grouped = + whole.length > 4 ? whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : whole; + const sign = text.startsWith("-") ? "-" : ""; + return fraction !== undefined + ? `${sign}${grouped}.${fraction}` + : `${sign}${grouped}`; +} + +function formatTimestamp(value: unknown): string { + if (value instanceof Date) { + return Number.isNaN(value.getTime()) + ? EMPTY_CELL + : value.toISOString().replace("T", " ").slice(0, 19); + } + const match = TIMESTAMP.exec(String(value)); + if (!match) return String(value); + // Wall-clock text as written: the same for every viewer. + return `${match[1]} ${match[2]}${match[3] ?? ""}${match[4] === "Z" ? " UTC" : match[4] ? ` ${match[4]}` : ""}`; +} + +/** Formats one cell by its column kind, at full precision. */ +export function formatCell(value: unknown, kind: ColumnKind): string { + if (isEmpty(value)) return EMPTY_CELL; + switch (kind) { + case "number": + return formatNumber(value); + case "boolean": + return value ? "true" : "false"; + case "timestamp": + return formatTimestamp(value); + case "json": + return typeof value === "object" ? JSON.stringify(value) : String(value); + default: + return typeof value === "object" ? JSON.stringify(value) : String(value); + } +} diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 8a502abb6..0ef92108e 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -41,10 +41,10 @@ import type { DataTableLabels, DataTableProps } from "./types"; * - 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. + * keys are dropped), headed by the key in Title Case. 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. * * @param props - Props for the DataTable component * @param props.queryKey - The query key to fetch the data diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index 67126f908..0bcf0a179 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -16,13 +16,10 @@ import { ArrowUpDown } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { useAnalyticsQuery } from ".."; -import { - formatChartValue, - formatFieldLabel, - SAFE_KEY_REGEX, -} from "../lib/format"; +import { formatFieldLabel, SAFE_KEY_REGEX } from "../lib/format"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; +import { formatCell, inferColumnKind } from "./cell-format"; import { EmptyState } from "./empty"; import { ErrorState } from "./error"; import { LoadingSkeleton } from "./loading"; @@ -112,6 +109,9 @@ export function TableWrapper( .filter((key) => SAFE_KEY_REGEX.test(key)) .map((key) => { const formattedLabel = formatFieldLabel(key); + const kind = inferColumnKind( + processedData.map((row) => (row as Record)[key]), + ); return { accessorKey: key, header: ({ column }: { column: Column }) => { @@ -129,15 +129,16 @@ export function TableWrapper( ); }, cell: ({ row }: { row: Row }) => { - const value = row.getValue(key); - if (typeof value === "number" || Number.isFinite(Number(value))) { - return ( -
- {formatChartValue(Number(value), key)} -
- ); - } - return
{String(value)}
; + const text = formatCell(row.getValue(key), kind); + return ( +
+ {text} +
+ ); }, }; }); From a6a5c7fec5f385c2b214577a36804355352553b9 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:36:46 +0000 Subject: [PATCH 079/151] feat(appkit-ui): add a data prop to DataTable DataTable could only fetch by queryKey, so it could not show stub rows while building the UI, Lakebase rows, or a result already fetched for a chart. It now takes `data` (rows or an Arrow Table, the same contract as chart `data`) with optional `loading` and `error`, as a discriminated alternative to queryKey/parameters. TableWrapper is split into a query source and a rows source over one table core; Arrow input is converted to rows once per input so the table does not reset each render. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 48 +++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 16 ++-- .../src/react/table/table-wrapper.tsx | 81 +++++++++++++++++-- packages/appkit-ui/src/react/table/types.ts | 46 ++++++++--- 4 files changed, 168 insertions(+), 23 deletions(-) create mode 100644 packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx new file mode 100644 index 000000000..d8087d79b --- /dev/null +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -0,0 +1,48 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { tableFromArrays } from "apache-arrow"; +import { afterEach, describe, expect, test, vi } from "vitest"; + +const mockUseAnalyticsQuery = vi.fn(); + +vi.mock("../../hooks/use-analytics-query", () => ({ + useAnalyticsQuery: (...args: unknown[]) => mockUseAnalyticsQuery(...args), +})); + +import { DataTable } from "../data-table"; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("DataTable data mode", () => { + test("renders rows passed as data without fetching", () => { + render( + , + ); + expect(mockUseAnalyticsQuery).not.toHaveBeenCalled(); + expect(screen.getByText("EMEA")).toBeTruthy(); + expect(screen.getByText("APAC")).toBeTruthy(); + }); + + test("accepts an Arrow Table", () => { + const table = tableFromArrays({ + region: ["EMEA", "AMER"], + orders: Int32Array.from([3, 4]), + }); + render(); + expect(screen.getByText("AMER")).toBeTruthy(); + }); + + test("shows loading and error states in data mode", () => { + const { rerender } = render(); + expect(screen.queryByText("No data available")).toBeNull(); + rerender(); + expect(screen.getByText(/boom/)).toBeTruthy(); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 0ef92108e..6a3987aa0 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -26,7 +26,7 @@ import { TableRow, } from "../ui/table"; import { TableWrapper } from "./table-wrapper"; -import type { DataTableLabels, DataTableProps } from "./types"; +import type { DataTableLabels, DataTableProps, TableDataSource } from "./types"; /** * Production-ready data table with automatic data fetching and state management @@ -63,6 +63,9 @@ import type { DataTableLabels, DataTableProps } from "./types"; * filterPlaceholder="Filter by email..." * /> * @example + * // Data mode: rows you already have (stub rows, Lakebase rows, or a result shared with a chart) + * + * @example * // full control mode * * {(table) => ( @@ -77,8 +80,6 @@ import type { DataTableLabels, DataTableProps } from "./types"; */ export function DataTable(props: DataTableProps) { const { - parameters, - queryKey, filterColumn, filterPlaceholder, transform, @@ -107,8 +108,7 @@ export function DataTable(props: DataTableProps) { return ( ); } + +function dataSource(props: DataTableProps): TableDataSource { + return props.data !== undefined + ? { data: props.data, loading: props.loading, error: props.error } + : { queryKey: props.queryKey, parameters: props.parameters }; +} diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index 0bcf0a179..ff2104481 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -12,10 +12,13 @@ import { useReactTable, type VisibilityState, } from "@tanstack/react-table"; +import type { Table as ArrowTable } from "apache-arrow"; import { ArrowUpDown } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { useAnalyticsQuery } from ".."; +import type { ChartData, ChartDataInput } from "../charts/types"; +import { isArrowTable } from "../charts/types"; import { formatFieldLabel, SAFE_KEY_REGEX } from "../lib/format"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; @@ -54,9 +57,70 @@ const EMPTY_DATA: never[] = []; export function TableWrapper( props: TableWrapperProps, ) { - const { + if (props.data !== undefined) { + return {...props} data={props.data} />; + } + return {...props} />; +} + +function RowsTable( + props: TableWrapperProps & { data: ChartDataInput }, +) { + const { data, loading, error, ...rest } = props; + // A fresh array per render would reset the table and loop; convert once per input. + const rows = useMemo(() => toRows(data), [data]); + return ( + + {...rest} + data={rows} + loading={loading ?? false} + error={error ?? null} + /> + ); +} + +function toRows(data: ChartDataInput): T[] { + return isArrowTable(data as ChartData) + ? Array.from(data as ArrowTable, (row) => ({ ...row.toJSON() }) as T) + : (data as T[]); +} + +type QueryTableProps = TableWrapperProps & { + queryKey: string; +}; + +function QueryTable( + props: QueryTableProps, +) { + const { queryKey, parameters, ...rest } = props; + const { data, loading, error } = useAnalyticsQuery( queryKey, parameters, + ); + return ( + + {...rest} + data={data ?? null} + loading={loading} + error={error} + /> + ); +} + +type TableCoreProps = Omit< + TableWrapperProps, + "data" | "loading" | "error" | "queryKey" | "parameters" +> & { + data: TRaw[] | null; + loading: boolean; + error: string | Error | null | undefined; +}; + +function TableCore(props: TableCoreProps) { + const { + data, + loading, + error, transformer, children, className, @@ -72,11 +136,6 @@ export function TableWrapper( const [columnVisibility, setColumnVisibility] = useState({}); const [rowSelection, setRowSelection] = useState({}); - const { data, loading, error } = useAnalyticsQuery( - queryKey, - parameters, - ); - useEffect(() => { if (onRowSelectionChange && enableRowSelection) { onRowSelectionChange(rowSelection); @@ -209,7 +268,15 @@ export function TableWrapper( if (loading) return ; if (error) return ( - + ); if (!hasData) return ; diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index d8740ba46..d38365123 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -1,15 +1,41 @@ import type { RowSelectionState, Table } from "@tanstack/react-table"; +import type { ChartDataInput } from "../charts/types"; + +/** Where a table's rows come from: an analytics query, or rows you already have. */ +export type TableDataSource = + | { + /** The query key to fetch the data */ + queryKey: string; + /** The parameters to pass to the query */ + parameters: Record; + data?: never; + loading?: never; + error?: never; + } + | { + /** + * 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. + */ + data: ChartDataInput; + /** Show the loading state (data mode). */ + loading?: boolean; + /** Show an error state (data mode). */ + error?: string | Error | null; + queryKey?: never; + parameters?: never; + }; + /** * Props for the TableWrapper component * @template TRaw - The raw data type returned by the analytics query * @template TProcessed - The processed data type after transformation */ -export interface TableWrapperProps { - /** The query key to fetch the data */ - queryKey: string; - /** The parameters to pass to the query */ - parameters: Record; +export type TableWrapperProps = TableDataSource & + TableWrapperOptions; + +interface TableWrapperOptions { /** * Optional function to transform raw data before creating table. * A new function reference re-runs it and resets the table to the first page, @@ -33,12 +59,10 @@ export interface TableWrapperProps { pageSize?: number; } -/** Props for the DataTable component */ -export interface DataTableProps { - /** The query key to fetch the data */ - queryKey: string; - /** The parameters to pass to the query */ - parameters: Record; +/** Props for the DataTable component: a data source (`queryKey` or `data`) plus options. */ +export type DataTableProps = TableDataSource & DataTableOptions; + +interface DataTableOptions { /** The column to filter by */ filterColumn?: string; /** Optional placeholder for the filter input */ From 21fc1172b39dce6dae5461126470b77b7b7bd29c Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:38:40 +0000 Subject: [PATCH 080/151] feat(appkit-ui): add a columns prop to DataTable and keep non-identifier keys Label, order, format, alignment, width and cell content could only be changed by rebuilding the table through children(table), and keys that were not plain identifiers were dropped silently, so an unaliased count(1) column disappeared. DataTable and TableWrapper now take `columns` ({ key, label, format, align, width, cell }) and show them in order; without it every key of the first row is shown, read with accessorFn so keys with dots or brackets work, and a non-identifier key is labelled as written. A column key missing from the rows logs a warning with the available keys. DataTableColumn, DataTableColumnFormat, DataTableLabels and DataTableProps are now exported. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 48 ++++++++ .../appkit-ui/src/react/table/data-table.tsx | 10 +- packages/appkit-ui/src/react/table/index.ts | 6 + .../src/react/table/table-wrapper.tsx | 108 ++++++++++++------ packages/appkit-ui/src/react/table/types.ts | 32 ++++++ 5 files changed, 163 insertions(+), 41 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index d8087d79b..74125aa6f 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -46,3 +46,51 @@ describe("DataTable data mode", () => { expect(screen.getByText(/boom/)).toBeTruthy(); }); }); + +describe("DataTable columns", () => { + const rows = [ + { "count(1)": 3, region: "EMEA", growth_pct: 12.5, cost_center: 4521 }, + ]; + + test("keeps keys that are not identifiers", () => { + render(); + expect(screen.getByText("count(1)")).toBeTruthy(); + expect(screen.getByText("3")).toBeTruthy(); + }); + + test("never formats by name: no USD for cost or growth keys", () => { + render(); + expect(screen.getByText("12.5")).toBeTruthy(); + expect(screen.getByText("4521")).toBeTruthy(); + expect(screen.queryByText(/\$/)).toBeNull(); + }); + + test("columns sets order, label, format, alignment and custom cells", () => { + render( + `${v}%`, + align: "center", + }, + { key: "cost_center", cell: (v) => cc }, + ]} + />, + ); + expect(screen.getByText("Sales region")).toBeTruthy(); + expect(screen.getByText("12.5%").className).toContain("text-center"); + expect(screen.getByText("cc").getAttribute("href")).toBe("/cc/4521"); + expect(screen.queryByText("count(1)")).toBeNull(); + }); + + test("warns about a column key that is not in the rows", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + render(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('"regoin"')); + warn.mockRestore(); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 6a3987aa0..a5962df2c 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -40,8 +40,8 @@ import type { DataTableLabels, DataTableProps, TableDataSource } from "./types"; * - 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. Cells are formatted by the column's type, inferred from all + * 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. @@ -89,6 +89,7 @@ export function DataTable(props: DataTableProps) { className, enableRowSelection, onRowSelectionChange, + columns, children, pageSize = 10, pageSizeOptions = [10, 25, 50, 100], @@ -113,6 +114,7 @@ export function DataTable(props: DataTableProps) { testId={testId} className={className} transformer={transform} + columns={columns} enableRowSelection={enableRowSelection} onRowSelectionChange={onRowSelectionChange} pageSize={pageSize} @@ -177,13 +179,13 @@ export function DataTable(props: DataTableProps) { return ( column.toggleVisibility(!!value) } > - {formatFieldLabel(column.id)} + {(column.columnDef.meta as { label?: string }) + ?.label ?? formatFieldLabel(column.id)} ); })} diff --git a/packages/appkit-ui/src/react/table/index.ts b/packages/appkit-ui/src/react/table/index.ts index ff4283998..b19712b44 100644 --- a/packages/appkit-ui/src/react/table/index.ts +++ b/packages/appkit-ui/src/react/table/index.ts @@ -1 +1,7 @@ export * from "./data-table"; +export type { + DataTableColumn, + DataTableColumnFormat, + DataTableLabels, + DataTableProps, +} from "./types"; diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index ff2104481..f1f604782 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -20,15 +20,21 @@ import { useAnalyticsQuery } from ".."; import type { ChartData, ChartDataInput } from "../charts/types"; import { isArrowTable } from "../charts/types"; import { formatFieldLabel, SAFE_KEY_REGEX } from "../lib/format"; +import { cn } from "../lib/utils"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; import { formatCell, inferColumnKind } from "./cell-format"; import { EmptyState } from "./empty"; import { ErrorState } from "./error"; import { LoadingSkeleton } from "./loading"; -import type { TableWrapperProps } from "./types"; +import type { DataTableColumn, TableWrapperProps } from "./types"; const CHECKBOX_COLUMN_WIDTH = 40; +const ALIGN_CLASS = { + left: "text-left", + center: "text-center", + right: "text-right", +} as const; const EMPTY_DATA: never[] = []; /** @@ -122,6 +128,7 @@ function TableCore(props: TableCoreProps) { loading, error, transformer, + columns, children, className, ariaLabel, @@ -164,43 +171,70 @@ function TableCore(props: TableCoreProps) { return []; } - const dataColumns = Object.keys(processedData[0] as object) - .filter((key) => SAFE_KEY_REGEX.test(key)) - .map((key) => { - const formattedLabel = formatFieldLabel(key); - const kind = inferColumnKind( - processedData.map((row) => (row as Record)[key]), + const firstRow = processedData[0] as Record; + const configs: DataTableColumn[] = + columns ?? Object.keys(firstRow).map((key) => ({ key })); + for (const config of configs) { + if (!(config.key in firstRow)) { + console.warn( + `[DataTable] Column "${config.key}" is not in the rows. Available keys: ${Object.keys(firstRow).join(", ")}`, ); - return { - accessorKey: key, - header: ({ column }: { column: Column }) => { - return ( - - ); - }, - cell: ({ row }: { row: Row }) => { - const text = formatCell(row.getValue(key), kind); - return ( -
- {text} -
+ } + } + + const dataColumns = configs.map((config) => { + const key = config.key; + const formattedLabel = + config.label ?? + (SAFE_KEY_REGEX.test(key) ? formatFieldLabel(key) : key); + const format = config.format; + const kind = + typeof format === "string" + ? format + : inferColumnKind( + processedData.map((row) => (row as Record)[key]), ); - }, - }; - }); + const align = config.align ?? (kind === "number" ? "right" : "left"); + return { + id: key, + // accessorFn, not accessorKey: a key with dots or brackets is read as written. + accessorFn: (row: TProcessed) => (row as Record)[key], + meta: { label: formattedLabel, align }, + ...(config.width !== undefined ? { size: config.width } : {}), + header: ({ column }: { column: Column }) => { + return ( + + ); + }, + cell: ({ row }: { row: Row }) => { + const value = row.getValue(key); + const content = config.cell + ? config.cell(value, row.original) + : typeof format === "function" + ? format(value, row.original) + : formatCell(value, kind); + return ( +
+ {content} +
+ ); + }, + }; + }); if (enableRowSelection) { return [ @@ -239,7 +273,7 @@ function TableCore(props: TableCoreProps) { } return dataColumns; - }, [hasData, processedData, enableRowSelection]); + }, [hasData, processedData, enableRowSelection, columns]); const table = useReactTable({ data: processedData, diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index d38365123..c7867fa74 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -2,6 +2,31 @@ import type { RowSelectionState, Table } from "@tanstack/react-table"; import type { ChartDataInput } from "../charts/types"; +/** How a column's cells are formatted when no `cell` renderer is given. */ +export type DataTableColumnFormat = + | "number" + | "text" + | "boolean" + | "date" + | "timestamp" + | "json"; + +/** One column of a DataTable. Columns are shown in the order given. */ +export interface DataTableColumn { + /** Row key to read. Any key works, including ones like `count(1)`. */ + key: string; + /** Header text. Defaults to the key in Title Case (or the key as written when it is not an identifier). */ + label?: string; + /** Cell format, or a function returning the cell text. Defaults to the type inferred from the values. */ + format?: DataTableColumnFormat | ((value: unknown, row: TRow) => string); + /** Text alignment. Defaults to right for numbers, left otherwise. */ + align?: "left" | "center" | "right"; + /** Column width in pixels. */ + width?: number; + /** Custom cell content (links, badges, actions). Overrides `format`. */ + cell?: (value: unknown, row: TRow) => React.ReactNode; +} + /** Where a table's rows come from: an analytics query, or rows you already have. */ export type TableDataSource = | { @@ -36,6 +61,8 @@ export type TableWrapperProps = TableDataSource & TableWrapperOptions; interface TableWrapperOptions { + /** Columns to show, in order. Defaults to every key of the first row. */ + columns?: DataTableColumn[]; /** * Optional function to transform raw data before creating table. * A new function reference re-runs it and resets the table to the first page, @@ -63,6 +90,11 @@ interface TableWrapperOptions { export type DataTableProps = TableDataSource & DataTableOptions; interface DataTableOptions { + /** + * 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. + */ + columns?: DataTableColumn[]; /** The column to filter by */ filterColumn?: string; /** Optional placeholder for the filter input */ From 386bc6807c643d3bfda407023b52620c9faf6aa5 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:39:33 +0000 Subject: [PATCH 081/151] fix(appkit-ui): align DataTable headers with their column type Headers were always left-aligned while numeric cells were right-aligned, so number columns read as misaligned. The header now follows the column alignment (right for numbers, the `align` from `columns` when set). Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 10 +++++++ .../src/react/table/table-wrapper.tsx | 27 ++++++++++++------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index 74125aa6f..513c2cc83 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -94,3 +94,13 @@ describe("DataTable columns", () => { warn.mockRestore(); }); }); + +describe("DataTable header alignment", () => { + test("a numeric column's header is right-aligned like its cells", () => { + render(); + const numericHeader = screen.getByText("Orders").closest("div"); + const textHeader = screen.getByText("Region").closest("div"); + expect(numericHeader?.className).toContain("justify-end"); + expect(textHeader?.className).toContain("justify-start"); + }); +}); diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index f1f604782..09dfb2e07 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -35,6 +35,11 @@ const ALIGN_CLASS = { center: "text-center", right: "text-right", } as const; +const HEADER_JUSTIFY = { + left: "justify-start", + center: "justify-center", + right: "justify-end", +} as const; const EMPTY_DATA: never[] = []; /** @@ -203,16 +208,18 @@ function TableCore(props: TableCoreProps) { ...(config.width !== undefined ? { size: config.width } : {}), header: ({ column }: { column: Column }) => { return ( - +
+ +
); }, cell: ({ row }: { row: Row }) => { From d6300762b8ac97115fe8870b537a5b3c7e26a7f1 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:40:28 +0000 Subject: [PATCH 082/151] feat(appkit-ui): show DataTable sort direction, set aria-sort, add defaultSort The sort icon never showed a direction, headers had no aria-sort, and there was no way to start sorted. Sorted headers now show an up or down arrow (a faint double arrow when unsorted), each sortable header sets aria-sort, and `defaultSort={{ key, desc }}` sets the initial sort. DataTableSort is exported. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 21 +++++++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 12 +++++++++++ packages/appkit-ui/src/react/table/index.ts | 1 + .../src/react/table/table-wrapper.tsx | 19 ++++++++++++++--- packages/appkit-ui/src/react/table/types.ts | 12 +++++++++++ 5 files changed, 62 insertions(+), 3 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index 513c2cc83..06a250af5 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -104,3 +104,24 @@ describe("DataTable header alignment", () => { expect(textHeader?.className).toContain("justify-start"); }); }); + +describe("DataTable sorting", () => { + const rows = [ + { region: "A", orders: 1 }, + { region: "B", orders: 3 }, + { region: "C", orders: 2 }, + ]; + + test("defaultSort sorts and headers expose aria-sort", () => { + render( + , + ); + const cells = screen.getAllByRole("cell").map((c) => c.textContent); + expect(cells.slice(0, 2)).toEqual(["B", "3"]); + const headers = screen.getAllByRole("columnheader"); + expect(headers.map((h) => h.getAttribute("aria-sort"))).toEqual([ + "none", + "descending", + ]); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index a5962df2c..261c93ea8 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -90,6 +90,7 @@ export function DataTable(props: DataTableProps) { enableRowSelection, onRowSelectionChange, columns, + defaultSort, children, pageSize = 10, pageSizeOptions = [10, 25, 50, 100], @@ -115,6 +116,7 @@ export function DataTable(props: DataTableProps) { className={className} transformer={transform} columns={columns} + defaultSort={defaultSort} enableRowSelection={enableRowSelection} onRowSelectionChange={onRowSelectionChange} pageSize={pageSize} @@ -200,9 +202,19 @@ export function DataTable(props: DataTableProps) { {headerGroup.headers.map((header) => { const isSelectColumn = header.column.id === "select"; + const sorted = header.column.getIsSorted(); return ( (props: TableCoreProps) { error, transformer, columns, + defaultSort, children, className, ariaLabel, @@ -143,7 +144,11 @@ function TableCore(props: TableCoreProps) { pageSize = 10, } = props; - const [sorting, setSorting] = useState([]); + const [sorting, setSorting] = useState(() => + defaultSort + ? [{ id: defaultSort.key, desc: defaultSort.desc ?? false }] + : [], + ); const [columnFilters, setColumnFilters] = useState([]); const [columnVisibility, setColumnVisibility] = useState({}); const [rowSelection, setRowSelection] = useState({}); @@ -217,7 +222,7 @@ function TableCore(props: TableCoreProps) { className={cn("h-8 px-2", align === "right" && "-mr-2")} > {formattedLabel} - +
); @@ -328,3 +333,11 @@ function TableCore(props: TableCoreProps) { ); } + +function SortIcon({ direction }: { direction: false | "asc" | "desc" }) { + const className = "ml-2 h-4 w-4"; + if (direction === "asc") return ; + if (direction === "desc") + return ; + return ; +} diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index c7867fa74..9f320a9eb 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -60,7 +60,17 @@ export type TableDataSource = export type TableWrapperProps = TableDataSource & TableWrapperOptions; +/** Initial sort of a table. */ +export interface DataTableSort { + /** Column key to sort by. */ + key: string; + /** Sort descending. @default false */ + desc?: boolean; +} + interface TableWrapperOptions { + /** Initial sort. */ + defaultSort?: DataTableSort; /** Columns to show, in order. Defaults to every key of the first row. */ columns?: DataTableColumn[]; /** @@ -90,6 +100,8 @@ interface TableWrapperOptions { export type DataTableProps = TableDataSource & DataTableOptions; interface DataTableOptions { + /** Initial sort, e.g. `{ key: "revenue", desc: true }`. Headers show the direction and set `aria-sort`. */ + defaultSort?: DataTableSort; /** * 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. From 6c9ca57f6cf090a1d9b0ac2e1508e088db0524f7 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:41:48 +0000 Subject: [PATCH 083/151] feat(appkit-ui): add a toolbar prop to DataTable and search across columns The filter input and the Columns menu always rendered, and the filter matched one column (by default the first string column). `toolbar` (default true) can now be `false` or `{ search, columns }` to hide either part. Without `filterColumn` the search box matches any column, numbers, dates and JSON included; with `filterColumn` it still filters that column only. The input has an aria-label. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 32 ++++- .../appkit-ui/src/react/table/data-table.tsx | 121 +++++++++--------- .../src/react/table/table-wrapper.tsx | 22 ++++ packages/appkit-ui/src/react/table/types.ts | 7 +- 4 files changed, 122 insertions(+), 60 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index 06a250af5..c14375c8e 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { tableFromArrays } from "apache-arrow"; import { afterEach, describe, expect, test, vi } from "vitest"; @@ -125,3 +125,33 @@ describe("DataTable sorting", () => { ]); }); }); + +describe("DataTable toolbar", () => { + const rows = [ + { region: "EMEA", owner: "ana", orders: 12 }, + { region: "APAC", owner: "bo", orders: 70 }, + ]; + + test("toolbar={false} hides the search box and Columns menu", () => { + render(); + expect(screen.queryByRole("textbox")).toBeNull(); + expect(screen.queryByText("Columns")).toBeNull(); + }); + + test("toolbar object hides one part", () => { + render(); + expect(screen.getByRole("textbox")).toBeTruthy(); + expect(screen.queryByText("Columns")).toBeNull(); + }); + + test("search matches any column, numbers included", () => { + render(); + const input = screen.getByRole("textbox"); + fireEvent.change(input, { target: { value: "bo" } }); + expect(screen.queryByText("EMEA")).toBeNull(); + expect(screen.getByText("APAC")).toBeTruthy(); + fireEvent.change(input, { target: { value: "12" } }); + expect(screen.getByText("EMEA")).toBeTruthy(); + expect(screen.queryByText("APAC")).toBeNull(); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 261c93ea8..8483a68bd 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -91,6 +91,7 @@ export function DataTable(props: DataTableProps) { onRowSelectionChange, columns, defaultSort, + toolbar = true, children, pageSize = 10, pageSizeOptions = [10, 25, 50, 100], @@ -126,16 +127,21 @@ export function DataTable(props: DataTableProps) { return children(table); } - const data = table.options.data; - - const defaultFilterColumn = - filterColumn || - (data && data.length > 0 - ? Object.keys(data[0] as Record).find( - (key) => - typeof (data[0] as Record)[key] === "string", - ) - : null); + const showSearch = + toolbar !== false && (toolbar === true || toolbar.search !== false); + const showColumnsMenu = + toolbar !== false && (toolbar === true || toolbar.columns !== false); + // With `filterColumn`, the input filters that column; otherwise it searches every column. + const filterTarget = filterColumn + ? table.getColumn(filterColumn) + : undefined; + const searchValue = filterTarget + ? ((filterTarget.getFilterValue() as string) ?? "") + : ((table.getState().globalFilter as string) ?? ""); + const setSearchValue = (value: string) => + filterTarget + ? filterTarget.setFilterValue(value) + : table.setGlobalFilter(value); const totalRows = table.getFilteredRowModel().rows.length; const currentPage = table.getState().pagination.pageIndex + 1; @@ -146,54 +152,53 @@ export function DataTable(props: DataTableProps) { return (
-
- {defaultFilterColumn && ( - - table - .getColumn(defaultFilterColumn) - ?.setFilterValue(event.target.value) - } - className="max-w-sm" - /> - )} - - - - - - {table - .getAllColumns() - .filter((column) => column.getCanHide()) - .map((column) => { - return ( - - column.toggleVisibility(!!value) - } - > - {(column.columnDef.meta as { label?: string }) - ?.label ?? formatFieldLabel(column.id)} - - ); - })} - - -
+ {(showSearch || showColumnsMenu) && ( +
+ {showSearch && ( + setSearchValue(event.target.value)} + className="max-w-sm" + /> + )} + {showColumnsMenu && ( + + + + + + {table + .getAllColumns() + .filter((column) => column.getCanHide()) + .map((column) => { + return ( + + column.toggleVisibility(!!value) + } + > + {(column.columnDef.meta as { label?: string }) + ?.label ?? formatFieldLabel(column.id)} + + ); + })} + + + )} +
+ )}
diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index 01edbc876..96ea36667 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -150,6 +150,7 @@ function TableCore(props: TableCoreProps) { : [], ); const [columnFilters, setColumnFilters] = useState([]); + const [globalFilter, setGlobalFilter] = useState(""); const [columnVisibility, setColumnVisibility] = useState({}); const [rowSelection, setRowSelection] = useState({}); @@ -292,6 +293,10 @@ function TableCore(props: TableCoreProps) { columns: tableColumns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, + onGlobalFilterChange: setGlobalFilter, + globalFilterFn: matchesAnyText, + // Search every data column, numbers and dates included (TanStack's default skips non-strings). + getColumnCanGlobalFilter: (column) => column.id !== "select", getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), @@ -301,6 +306,7 @@ function TableCore(props: TableCoreProps) { state: { sorting, columnFilters, + globalFilter, columnVisibility, rowSelection, }, @@ -341,3 +347,19 @@ function SortIcon({ direction }: { direction: false | "asc" | "desc" }) { return ; return ; } + +function matchesAnyText( + row: Row, + columnId: string, + filter: unknown, +): boolean { + const needle = String(filter ?? "") + .trim() + .toLowerCase(); + if (!needle) return true; + const value = row.getValue(columnId); + if (value === null || value === undefined) return false; + const text = + typeof value === "object" ? JSON.stringify(value) : String(value); + return text.toLowerCase().includes(needle); +} diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index 9f320a9eb..b4c08253e 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -107,7 +107,12 @@ interface DataTableOptions { * Defaults to every key of the first row with the format inferred from the values. */ columns?: DataTableColumn[]; - /** The column to filter by */ + /** + * The toolbar above the table: a search box and a Columns menu. `false` hides it; an object hides either part. + * @default true + */ + toolbar?: boolean | { search?: boolean; columns?: boolean }; + /** Filter only this column. Without it, the search box matches any column. */ filterColumn?: string; /** Optional placeholder for the filter input */ filterPlaceholder?: string; From f7a732c124b6909eb0c1d1cce69555686c5e656e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:42:47 +0000 Subject: [PATCH 084/151] fix(appkit-ui): keep DataTable headers and wrapper on an empty result An empty result replaced the whole table with "No data available", dropping headers, className and testId. With `columns` the table now renders its headers and an empty "No results" row; without columns (no keys are known from zero rows) the empty state renders inside the wrapper so className, aria-label and testId stay. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 22 ++++++++++++++++ .../src/react/table/table-wrapper.tsx | 25 +++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index c14375c8e..bd76bb583 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -155,3 +155,25 @@ describe("DataTable toolbar", () => { expect(screen.queryByText("APAC")).toBeNull(); }); }); + +describe("DataTable empty result", () => { + test("keeps the headers from columns and shows an empty row", () => { + render( + , + ); + expect(screen.getByText("Region")).toBeTruthy(); + expect(screen.getByText("Orders")).toBeTruthy(); + expect(screen.getAllByText("No results found.").length).toBeGreaterThan(0); + expect(screen.getByTestId("orders")).toBeTruthy(); + }); + + test("keeps className and testId without columns", () => { + render(); + expect(screen.getByTestId("t").className).toContain("my-table"); + expect(screen.getByText("No data available")).toBeTruthy(); + }); +}); diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index 96ea36667..69b50e462 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -175,18 +175,22 @@ function TableCore(props: TableCoreProps) { ); const tableColumns = useMemo(() => { - if (!hasData) return []; + // An empty result still has headers when `columns` names them. + if (!hasData && !columns) return []; - if (!processedData[0] || typeof processedData[0] !== "object") { + if ( + hasData && + (!processedData[0] || typeof processedData[0] !== "object") + ) { console.warn("Invalid data format for DataTable"); return []; } - const firstRow = processedData[0] as Record; + const firstRow = (processedData[0] ?? {}) as Record; const configs: DataTableColumn[] = columns ?? Object.keys(firstRow).map((key) => ({ key })); for (const config of configs) { - if (!(config.key in firstRow)) { + if (hasData && !(config.key in firstRow)) { console.warn( `[DataTable] Column "${config.key}" is not in the rows. Available keys: ${Object.keys(firstRow).join(", ")}`, ); @@ -331,7 +335,18 @@ function TableCore(props: TableCoreProps) { /> ); - if (!hasData) return ; + // Keep the wrapper (className, testId) for an empty result. With known + // columns the table renders its headers and an empty row. + if (!hasData && tableColumns.length === 0) + return ( +
+ +
+ ); return (
From 900c2a8b45101ade637f3a4ef83af51d9c8f7a6e Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:45:34 +0000 Subject: [PATCH 085/151] fix(appkit-ui): size DataTable columns to content and add per-column truncate Every column was fixed at TanStack default 150 px, so fifteen columns needed 2,564 px in a 1,478 px card, and there was no wrap or truncate control. Columns now size to their content and only a `width` from `columns` (or the 40 px selection column) is fixed. `truncate` on a column cuts long text to one line with an ellipsis at 240 px or the given pixel width, with the full text as a tooltip. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 21 +++++++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 12 +++++++++-- .../src/react/table/table-wrapper.tsx | 13 +++++++++++- packages/appkit-ui/src/react/table/types.ts | 7 ++++++- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index bd76bb583..f2205fe79 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -177,3 +177,24 @@ describe("DataTable empty result", () => { expect(screen.getByText("No data available")).toBeTruthy(); }); }); + +describe("DataTable column widths", () => { + test("columns size to content unless a width is given", () => { + render( + , + ); + const [regionHead, noteHead] = screen.getAllByRole("columnheader"); + expect(regionHead.style.width).toBe("120px"); + expect(noteHead.style.width).toBe(""); + const note = screen.getByText("a very long note"); + expect(note.className).toContain("truncate"); + expect(note.style.maxWidth).toBe("80px"); + expect(note.getAttribute("title")).toBe("a very long note"); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 8483a68bd..bb878d630 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -221,7 +221,8 @@ export function DataTable(props: DataTableProps) { : "none" } style={{ - width: header.getSize(), + // Only an explicit width is fixed; other columns size to their content. + width: explicitWidth(header.column), position: "relative", }} className={ @@ -253,7 +254,7 @@ export function DataTable(props: DataTableProps) { (props: TableCoreProps) { id: key, // accessorFn, not accessorKey: a key with dots or brackets is read as written. accessorFn: (row: TProcessed) => (row as Record)[key], - meta: { label: formattedLabel, align }, + meta: { label: formattedLabel, align, width: config.width }, ...(config.width !== undefined ? { size: config.width } : {}), header: ({ column }: { column: Column }) => { return ( @@ -239,12 +239,22 @@ function TableCore(props: TableCoreProps) { : typeof format === "function" ? format(value, row.original) : formatCell(value, kind); + const truncate = config.truncate; return (
{content}
@@ -257,6 +267,7 @@ function TableCore(props: TableCoreProps) { return [ { id: "select", + meta: { width: CHECKBOX_COLUMN_WIDTH }, maxSize: CHECKBOX_COLUMN_WIDTH, minSize: CHECKBOX_COLUMN_WIDTH, header: ({ table }: { table: Table }) => ( diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index b4c08253e..192c3682b 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -21,8 +21,13 @@ export interface DataTableColumn { format?: DataTableColumnFormat | ((value: unknown, row: TRow) => string); /** Text alignment. Defaults to right for numbers, left otherwise. */ align?: "left" | "center" | "right"; - /** Column width in pixels. */ + /** Column width in pixels. Without it the column sizes to its content. */ width?: number; + /** + * Cut long text to one line with an ellipsis; the full text is in the tooltip. `true` caps the cell at 240 px, + * a number at that many pixels. + */ + truncate?: boolean | number; /** Custom cell content (links, badges, actions). Overrides `format`. */ cell?: (value: unknown, row: TRow) => React.ReactNode; } From d0cbb98fb332c644b00fa7a2ca0748dd15f2bc2b Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:46:44 +0000 Subject: [PATCH 086/151] feat(appkit-ui): add onRowClick and onSelectionChange to DataTable Row selection only reported a TanStack index map and the rows were not exposed; there was no row click. `onSelectionChange(rows)` now receives the selected row objects, and `onRowClick(row)` fires on a row click or Enter on a focused row (rows become focusable; clicks on checkboxes, buttons and links inside the row are ignored). `onRowSelectionChange` is kept. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/data-table.test.tsx | 33 +++++++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 29 ++++++++++++++++ .../src/react/table/table-wrapper.tsx | 11 +++++++ packages/appkit-ui/src/react/table/types.ts | 8 ++++- 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index f2205fe79..5d2d18cc7 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -198,3 +198,36 @@ describe("DataTable column widths", () => { expect(note.getAttribute("title")).toBe("a very long note"); }); }); + +describe("DataTable row events", () => { + const rows = [ + { region: "EMEA", orders: 12 }, + { region: "APAC", orders: 70 }, + ]; + + test("onRowClick receives the row, by click or Enter", () => { + const onRowClick = vi.fn(); + render(); + const row = screen.getByText("APAC").closest("tr") as HTMLElement; + fireEvent.click(row); + fireEvent.keyDown(row, { key: "Enter" }); + expect(onRowClick).toHaveBeenNthCalledWith(1, rows[1]); + expect(onRowClick).toHaveBeenNthCalledWith(2, rows[1]); + }); + + test("onSelectionChange receives the selected rows; a checkbox click is not a row click", () => { + const onSelectionChange = vi.fn(); + const onRowClick = vi.fn(); + render( + , + ); + fireEvent.click(screen.getAllByLabelText("Select row")[0]); + expect(onSelectionChange).toHaveBeenLastCalledWith([rows[0]]); + expect(onRowClick).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index bb878d630..2275d843c 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -89,6 +89,8 @@ export function DataTable(props: DataTableProps) { className, enableRowSelection, onRowSelectionChange, + onSelectionChange, + onRowClick, columns, defaultSort, toolbar = true, @@ -120,6 +122,7 @@ export function DataTable(props: DataTableProps) { defaultSort={defaultSort} enableRowSelection={enableRowSelection} onRowSelectionChange={onRowSelectionChange} + onSelectionChange={onSelectionChange} pageSize={pageSize} > {(table) => { @@ -247,6 +250,24 @@ export function DataTable(props: DataTableProps) { { + if (isControlTarget(event.target)) return; + onRowClick(row.original); + }, + onKeyDown: (event: React.KeyboardEvent) => { + if ( + event.key === "Enter" && + event.target === event.currentTarget + ) { + onRowClick(row.original); + } + }, + } + : {})} > {row.getVisibleCells().map((cell) => { const isSelectColumn = cell.column.id === "select"; @@ -355,3 +376,11 @@ function explicitWidth(column: { // TanStack fills `size` with 150 for every column, so read the width the caller set. return (column.columnDef.meta as { width?: number } | undefined)?.width; } + +/** A click on a checkbox, button or link inside the row is not a row click. */ +function isControlTarget(target: EventTarget | null): boolean { + return ( + target instanceof Element && + target.closest('button, a, input, [role="checkbox"]') !== null + ); +} diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index 9e7a891f4..dc216875c 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -141,6 +141,7 @@ function TableCore(props: TableCoreProps) { testId, enableRowSelection = false, onRowSelectionChange, + onSelectionChange, pageSize = 10, } = props; @@ -332,6 +333,16 @@ function TableCore(props: TableCoreProps) { }, }); + // Report the selected rows themselves, not only TanStack's index map. + useEffect(() => { + if (onSelectionChange && enableRowSelection) { + onSelectionChange( + table.getSelectedRowModel().rows.map((row) => row.original), + ); + } + // `table` is stable; the selection state drives this effect. + }, [rowSelection, onSelectionChange, enableRowSelection]); + if (loading) return ; if (error) return ( diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index 192c3682b..f09d60da0 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -97,6 +97,8 @@ interface TableWrapperOptions { enableRowSelection?: boolean; /** Callback function to handle row selection changes */ onRowSelectionChange?: (rowSelection: RowSelectionState) => void; + /** Called with the selected rows whenever the selection changes */ + onSelectionChange?: (rows: TProcessed[]) => void; /** Number of rows to display per page */ pageSize?: number; } @@ -138,8 +140,12 @@ interface DataTableOptions { className?: string; /** Enable row selection with checkboxes */ enableRowSelection?: boolean; - /** Callback function to handle row selection changes */ + /** Callback function to handle row selection changes (TanStack index map; prefer `onSelectionChange`) */ onRowSelectionChange?: (rowSelection: RowSelectionState) => void; + /** Called with the selected rows themselves whenever the selection changes. Needs `enableRowSelection`. */ + onSelectionChange?: (rows: any[]) => void; + /** Called with the row when a row is clicked, or activated with Enter. Rows become focusable. */ + onRowClick?: (row: any) => void; /** Optional children for full control mode */ children?: (table: Table) => React.ReactNode; /** Number of rows to display per page */ From ea40a2717057adeec06f53abd4ee6deba07cd4fc Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:48:12 +0000 Subject: [PATCH 087/151] fix(appkit-ui): keep the DataTable page when an inline transform re-runs An inline `transform` is a new function every render, so it re-ran, produced a new array and reset the table to page 1 (with about 45 columns the tab froze, FEEDBACK-42185). The table now keeps its previous rows when the new output holds the same rows (shallow compare), so the page, columns and sort survive re-renders; a transform that returns different rows still applies. DataTable also accepts `transformer` as an alias of `transform`, the name charts use. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../table/__tests__/table-wrapper.test.tsx | 33 ++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 3 +- .../src/react/table/table-wrapper.tsx | 43 ++++++++++++++----- packages/appkit-ui/src/react/table/types.ts | 14 +++--- 4 files changed, 73 insertions(+), 20 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx b/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx index a808947b0..0afb6f345 100644 --- a/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx @@ -115,3 +115,36 @@ describe("TableWrapper", () => { expect(pageIndex).toBe(1); }); }); + +describe("TableWrapper inline transformer", () => { + test("keeps the page across re-renders with a new inline transformer", async () => { + mockUseAnalyticsQuery.mockReturnValue({ + data: rows, + loading: false, + error: null, + }); + let pageIndex = -1; + let goToNextPage = () => {}; + const renderTable = () => ( + data.map((row) => ({ ...row }))} + > + {(table) => { + pageIndex = table.getState().pagination.pageIndex; + goToNextPage = () => table.nextPage(); + return {table.getRowModel().rows.length}; + }} + + ); + const { rerender } = render(renderTable()); + await settle(); + goToNextPage(); + await settle(); + expect(pageIndex).toBe(1); + rerender(renderTable()); + await settle(); + expect(pageIndex).toBe(1); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index 2275d843c..e568fe772 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -83,6 +83,7 @@ export function DataTable(props: DataTableProps) { filterColumn, filterPlaceholder, transform, + transformer, labels, ariaLabel, testId, @@ -117,7 +118,7 @@ export function DataTable(props: DataTableProps) { ariaLabel={ariaLabel} testId={testId} className={className} - transformer={transform} + transformer={transform ?? transformer} columns={columns} defaultSort={defaultSort} enableRowSelection={enableRowSelection} diff --git a/packages/appkit-ui/src/react/table/table-wrapper.tsx b/packages/appkit-ui/src/react/table/table-wrapper.tsx index dc216875c..5d312626e 100644 --- a/packages/appkit-ui/src/react/table/table-wrapper.tsx +++ b/packages/appkit-ui/src/react/table/table-wrapper.tsx @@ -14,7 +14,7 @@ import { } from "@tanstack/react-table"; import type { Table as ArrowTable } from "apache-arrow"; import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useAnalyticsQuery } from ".."; import type { ChartData, ChartDataInput } from "../charts/types"; @@ -164,16 +164,20 @@ function TableCore(props: TableCoreProps) { const hasData = data && data.length > 0; // TanStack resets the page index (and re-renders) whenever `data` changes - // identity, so a fresh array per render loops forever. - const processedData = useMemo( - () => - hasData - ? transformer - ? transformer(data) - : (data as unknown as TProcessed[]) - : (EMPTY_DATA as TProcessed[]), - [hasData, data, transformer], - ); + // identity, so a fresh array per render loops forever. An inline transformer + // is a new function each render; keep the previous output when the new one + // holds the same rows, so the page and the column set survive re-renders. + const previousRef = useRef(null); + const processedData = useMemo(() => { + const next = hasData + ? transformer + ? transformer(data) + : (data as unknown as TProcessed[]) + : (EMPTY_DATA as TProcessed[]); + const previous = previousRef.current; + return previous && sameRows(previous, next) ? previous : next; + }, [hasData, data, transformer]); + previousRef.current = processedData; const tableColumns = useMemo(() => { // An empty result still has headers when `columns` names them. @@ -400,3 +404,20 @@ function matchesAnyText( typeof value === "object" ? JSON.stringify(value) : String(value); return text.toLowerCase().includes(needle); } + +/** Same length and every row has the same keys and values (shallow). */ +function sameRows(a: readonly T[], b: readonly T[]): boolean { + if (a === b) return true; + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + const x = a[i] as Record; + const y = b[i] as Record; + if (x === y) continue; + if (!x || !y || typeof x !== "object" || typeof y !== "object") + return false; + const keys = Object.keys(x); + if (keys.length !== Object.keys(y).length) return false; + for (const key of keys) if (!Object.is(x[key], y[key])) return false; + } + return true; +} diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index f09d60da0..2425a4cff 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -79,10 +79,8 @@ interface TableWrapperOptions { /** Columns to show, in order. Defaults to every key of the first row. */ columns?: DataTableColumn[]; /** - * Optional function to transform raw 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`. + * Optional function to transform raw 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: TRaw[]) => TProcessed[]; /** Render function that receives the TanStack Table instance */ @@ -124,12 +122,12 @@ interface DataTableOptions { /** Optional placeholder for the filter input */ filterPlaceholder?: string; /** - * 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`. + * 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. */ transform?: (data: any[]) => any[]; + /** Same as `transform`, under the name charts use. */ + transformer?: (data: any[]) => any[]; /** Optional labels for the DataTable component */ labels?: DataTableLabels; /** Optional accessibility label for the DataTable component */ From bac7c07cf95e3c61d87dacd3011d140439ec08ef Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:49:03 +0000 Subject: [PATCH 088/151] feat(appkit-ui): add a maxHeight prop to DataTable (server-side paging not done) Partial fix. The table body height was fixed at 600 px; `maxHeight` (pixels or a CSS length, default 600) now sets where the body scrolls under the sticky header. Not done: server-side page, sort and filter. All rows still arrive in one result and are sorted, filtered and paged in the browser. Doing it through query parameters needs a server contract first: the analytics plugin would have to accept page/sort/filter parameters that a query file declares and return a total row count alongside the page. That is a plugin and query-convention change, not a DataTable change. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../src/react/table/__tests__/data-table.test.tsx | 11 +++++++++++ packages/appkit-ui/src/react/table/data-table.tsx | 6 +++++- packages/appkit-ui/src/react/table/types.ts | 5 +++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx index 5d2d18cc7..dff266209 100644 --- a/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/data-table.test.tsx @@ -231,3 +231,14 @@ describe("DataTable row events", () => { expect(onRowClick).not.toHaveBeenCalled(); }); }); + +describe("DataTable maxHeight", () => { + test("defaults to 600 px and can be changed", () => { + const { container, rerender } = render(); + const scroller = () => + container.querySelector(".overflow-y-auto") as HTMLElement; + expect(scroller().style.maxHeight).toBe("600px"); + rerender(); + expect(scroller().style.maxHeight).toBe("50vh"); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index e568fe772..b8ba3fbb1 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -95,6 +95,7 @@ export function DataTable(props: DataTableProps) { columns, defaultSort, toolbar = true, + maxHeight, children, pageSize = 10, pageSizeOptions = [10, 25, 50, 100], @@ -204,7 +205,10 @@ export function DataTable(props: DataTableProps) { )}
-
+
{table.getHeaderGroups().map((headerGroup) => ( diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index 2425a4cff..36e111604 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -148,6 +148,11 @@ interface DataTableOptions { children?: (table: Table) => React.ReactNode; /** Number of rows to display per page */ pageSize?: number; + /** + * Height at which the table body scrolls (pixels or a CSS length), with the header kept in view. + * @default 600 + */ + maxHeight?: number | string; /** Options for the page size selector */ pageSizeOptions?: number[]; } From e94b618983fdee0cb8a8543fbffae6570c359cc3 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:49:50 +0000 Subject: [PATCH 089/151] fix(appkit-ui): make DataTable parameters optional `parameters` was required on DataTable and TableWrapper and optional on charts, so a query without parameters needed `parameters={{}}`. It is now optional in query mode, matching charts. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- .../react/table/__tests__/table-wrapper.test.tsx | 16 ++++++++++++++++ .../appkit-ui/src/react/table/data-table.tsx | 2 +- packages/appkit-ui/src/react/table/types.ts | 4 ++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx b/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx index 0afb6f345..5888c22af 100644 --- a/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx +++ b/packages/appkit-ui/src/react/table/__tests__/table-wrapper.test.tsx @@ -148,3 +148,19 @@ describe("TableWrapper inline transformer", () => { expect(pageIndex).toBe(1); }); }); + +describe("TableWrapper parameters", () => { + test("parameters are optional in query mode", () => { + mockUseAnalyticsQuery.mockReturnValue({ + data: rows, + loading: false, + error: null, + }); + render( + + {(table) => {table.getRowModel().rows.length}} + , + ); + expect(mockUseAnalyticsQuery).toHaveBeenCalledWith("q", undefined); + }); +}); diff --git a/packages/appkit-ui/src/react/table/data-table.tsx b/packages/appkit-ui/src/react/table/data-table.tsx index b8ba3fbb1..b63d989ae 100644 --- a/packages/appkit-ui/src/react/table/data-table.tsx +++ b/packages/appkit-ui/src/react/table/data-table.tsx @@ -48,7 +48,7 @@ import type { DataTableLabels, DataTableProps, TableDataSource } from "./types"; * * @param props - Props for the DataTable component * @param props.queryKey - The query key to fetch the data - * @param props.parameters - The parameters to pass to the query. Required - use `{}` if none. + * @param props.parameters - The parameters to pass to the query (optional) * @param props.filterColumn - The column to filter by * @param props.filterPlaceholder - The placeholder for the filter input * @param props.children - Optional children for full control mode diff --git a/packages/appkit-ui/src/react/table/types.ts b/packages/appkit-ui/src/react/table/types.ts index 36e111604..fefc3074e 100644 --- a/packages/appkit-ui/src/react/table/types.ts +++ b/packages/appkit-ui/src/react/table/types.ts @@ -37,8 +37,8 @@ export type TableDataSource = | { /** The query key to fetch the data */ queryKey: string; - /** The parameters to pass to the query */ - parameters: Record; + /** The parameters to pass to the query. Optional, as on charts. */ + parameters?: Record; data?: never; loading?: never; error?: never; From 97712c2603227054923094029b856c550fb2cbb7 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:52:18 +0000 Subject: [PATCH 090/151] docs(appkit-ui): document the defaults the charts actually use The docs listed defaults that differed from the runtime: bar orientation "vertical" (categories were horizontal), showLegend with no default (it is true), stacked as "Stack bars" (ignored on vertical bars), orientation on LineChart, colors without var(), and a 160 px height note. The prop comments now state the runtime rule, with the defaults="v3" variant where one applies (orientation, smooth, height, pie showLabels), and the chart and DataTable pages are regenerated from them, which also brings in the props added on this branch. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- docs/docs/api/appkit-ui/data/AreaChart.mdx | 24 ++++++++++----- docs/docs/api/appkit-ui/data/BarChart.mdx | 23 +++++++++----- docs/docs/api/appkit-ui/data/DataTable.mdx | 30 ++++++++++++------- docs/docs/api/appkit-ui/data/DonutChart.mdx | 20 ++++++++----- docs/docs/api/appkit-ui/data/HeatmapChart.mdx | 22 ++++++++++---- docs/docs/api/appkit-ui/data/LineChart.mdx | 24 ++++++++++----- docs/docs/api/appkit-ui/data/PieChart.mdx | 20 ++++++++----- docs/docs/api/appkit-ui/data/RadarChart.mdx | 17 +++++++---- docs/docs/api/appkit-ui/data/ScatterChart.mdx | 17 +++++++---- packages/appkit-ui/src/react/charts/types.ts | 10 +++++-- 10 files changed, 143 insertions(+), 64 deletions(-) diff --git a/docs/docs/api/appkit-ui/data/AreaChart.mdx b/docs/docs/api/appkit-ui/data/AreaChart.mdx index 59ce64da1..67d7cb472 100644 --- a/docs/docs/api/appkit-ui/data/AreaChart.mdx +++ b/docs/docs/api/appkit-ui/data/AreaChart.mdx @@ -54,26 +54,36 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/BarChart.mdx b/docs/docs/api/appkit-ui/data/BarChart.mdx index c016e9add..3582058fe 100644 --- a/docs/docs/api/appkit-ui/data/BarChart.mdx +++ b/docs/docs/api/appkit-ui/data/BarChart.mdx @@ -51,24 +51,33 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/DataTable.mdx b/docs/docs/api/appkit-ui/data/DataTable.mdx index 00c4fb15f..f30bdab3d 100644 --- a/docs/docs/api/appkit-ui/data/DataTable.mdx +++ b/docs/docs/api/appkit-ui/data/DataTable.mdx @@ -38,11 +38,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 +52,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`. | +| `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 | diff --git a/docs/docs/api/appkit-ui/data/DonutChart.mdx b/docs/docs/api/appkit-ui/data/DonutChart.mdx index 42bed7fb6..69ae163b8 100644 --- a/docs/docs/api/appkit-ui/data/DonutChart.mdx +++ b/docs/docs/api/appkit-ui/data/DonutChart.mdx @@ -48,25 +48,31 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/HeatmapChart.mdx b/docs/docs/api/appkit-ui/data/HeatmapChart.mdx index 48a959935..fe81900fe 100644 --- a/docs/docs/api/appkit-ui/data/HeatmapChart.mdx +++ b/docs/docs/api/appkit-ui/data/HeatmapChart.mdx @@ -65,26 +65,36 @@ 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`. | diff --git a/docs/docs/api/appkit-ui/data/LineChart.mdx b/docs/docs/api/appkit-ui/data/LineChart.mdx index eaa662d00..4456d3d90 100644 --- a/docs/docs/api/appkit-ui/data/LineChart.mdx +++ b/docs/docs/api/appkit-ui/data/LineChart.mdx @@ -53,25 +53,35 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/PieChart.mdx b/docs/docs/api/appkit-ui/data/PieChart.mdx index 60def78b4..e675c1f1c 100644 --- a/docs/docs/api/appkit-ui/data/PieChart.mdx +++ b/docs/docs/api/appkit-ui/data/PieChart.mdx @@ -48,25 +48,31 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/RadarChart.mdx b/docs/docs/api/appkit-ui/data/RadarChart.mdx index 9bb102b65..58ee2bbc6 100644 --- a/docs/docs/api/appkit-ui/data/RadarChart.mdx +++ b/docs/docs/api/appkit-ui/data/RadarChart.mdx @@ -52,23 +52,30 @@ 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. | diff --git a/docs/docs/api/appkit-ui/data/ScatterChart.mdx b/docs/docs/api/appkit-ui/data/ScatterChart.mdx index 0e395190a..cd87109fb 100644 --- a/docs/docs/api/appkit-ui/data/ScatterChart.mdx +++ b/docs/docs/api/appkit-ui/data/ScatterChart.mdx @@ -54,23 +54,30 @@ 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. | diff --git a/packages/appkit-ui/src/react/charts/types.ts b/packages/appkit-ui/src/react/charts/types.ts index 5e755115b..2773c0c26 100644 --- a/packages/appkit-ui/src/react/charts/types.ts +++ b/packages/appkit-ui/src/react/charts/types.ts @@ -96,7 +96,11 @@ export interface ChartUITokens { export interface ChartBaseProps { /** Chart title */ title?: string; - /** Show legend */ + /** + * 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. + * @default true + */ showLegend?: boolean; /** * Color palette to use. Auto-selected based on chart type if not specified. @@ -353,7 +357,7 @@ export interface BarChartSpecificProps * horizontal. */ orientation?: Orientation; - /** Stack bars */ + /** Stack the series, on vertical and horizontal bars. @default false */ stacked?: boolean; } @@ -418,7 +422,7 @@ export interface PieChartSpecificProps { * @default 0 (40 on DonutChart) */ innerRadius?: number; - /** Show labels on slices @default true */ + /** Show labels on slices. @default true (false with `defaults="v3"`, where the legend shows name, value and share) */ showLabels?: boolean; /** Label position @default "outside" */ labelPosition?: "outside" | "inside" | "center"; From 5916b71ccf5c0c366f2477ec17adfcc6148c2b11 Mon Sep 17 00:00:00 2001 From: Nikola Petrovski Date: Tue, 1 Dec 2026 22:53:09 +0000 Subject: [PATCH 091/151] docs(appkit-ui): import components from @databricks/appkit-ui/react in docs The generated Usage snippet on every component page imported from `@databricks/appkit-ui`, which has no root export, so copying it fails to resolve. The generator now writes `@databricks/appkit-ui/react` (71 pages regenerated), the analytics plugin page uses the same path, and the generator test checks that no chart page imports from the root. Co-authored-by: Isaac Signed-off-by: Nikola Petrovski --- docs/docs/api/appkit-ui/data/AreaChart.mdx | 2 +- docs/docs/api/appkit-ui/data/BarChart.mdx | 2 +- docs/docs/api/appkit-ui/data/DataTable.mdx | 2 +- docs/docs/api/appkit-ui/data/DonutChart.mdx | 2 +- docs/docs/api/appkit-ui/data/HeatmapChart.mdx | 2 +- docs/docs/api/appkit-ui/data/LineChart.mdx | 2 +- docs/docs/api/appkit-ui/data/PieChart.mdx | 2 +- docs/docs/api/appkit-ui/data/RadarChart.mdx | 2 +- docs/docs/api/appkit-ui/data/ScatterChart.mdx | 2 +- .../api/appkit-ui/files/DirectoryList.mdx | 2 +- .../api/appkit-ui/files/FileBreadcrumb.mdx | 2 +- docs/docs/api/appkit-ui/files/FileEntry.mdx | 2 +- .../api/appkit-ui/files/FilePreviewPanel.mdx | 2 +- .../api/appkit-ui/files/NewFolderInput.mdx | 2 +- docs/docs/api/appkit-ui/genie/GenieChat.mdx | 2 +- .../api/appkit-ui/genie/GenieChatInput.mdx | 2 +- .../api/appkit-ui/genie/GenieChatMessage.mdx | 2 +- .../appkit-ui/genie/GenieChatMessageList.mdx | 2 +- .../genie/GenieQueryVisualization.mdx | 2 +- docs/docs/api/appkit-ui/ui/Accordion.mdx | 8 ++-- docs/docs/api/appkit-ui/ui/Alert.mdx | 6 +-- docs/docs/api/appkit-ui/ui/AlertDialog.mdx | 22 ++++----- docs/docs/api/appkit-ui/ui/AspectRatio.mdx | 2 +- docs/docs/api/appkit-ui/ui/Avatar.mdx | 6 +-- docs/docs/api/appkit-ui/ui/Badge.mdx | 2 +- docs/docs/api/appkit-ui/ui/Breadcrumb.mdx | 14 +++--- docs/docs/api/appkit-ui/ui/Button.mdx | 2 +- docs/docs/api/appkit-ui/ui/ButtonGroup.mdx | 6 +-- docs/docs/api/appkit-ui/ui/Calendar.mdx | 4 +- docs/docs/api/appkit-ui/ui/Card.mdx | 14 +++--- docs/docs/api/appkit-ui/ui/Carousel.mdx | 10 ++-- docs/docs/api/appkit-ui/ui/Checkbox.mdx | 2 +- docs/docs/api/appkit-ui/ui/Collapsible.mdx | 6 +-- docs/docs/api/appkit-ui/ui/Command.mdx | 18 +++---- docs/docs/api/appkit-ui/ui/ContextMenu.mdx | 30 ++++++------ docs/docs/api/appkit-ui/ui/Dialog.mdx | 20 ++++---- docs/docs/api/appkit-ui/ui/Drawer.mdx | 20 ++++---- docs/docs/api/appkit-ui/ui/DropdownMenu.mdx | 30 ++++++------ docs/docs/api/appkit-ui/ui/Empty.mdx | 12 ++--- docs/docs/api/appkit-ui/ui/Field.mdx | 20 ++++---- docs/docs/api/appkit-ui/ui/FormControl.mdx | 12 ++--- docs/docs/api/appkit-ui/ui/HoverCard.mdx | 6 +-- docs/docs/api/appkit-ui/ui/Input.mdx | 2 +- docs/docs/api/appkit-ui/ui/InputGroup.mdx | 12 ++--- docs/docs/api/appkit-ui/ui/InputOTP.mdx | 8 ++-- docs/docs/api/appkit-ui/ui/Item.mdx | 20 ++++---- docs/docs/api/appkit-ui/ui/Kbd.mdx | 4 +- docs/docs/api/appkit-ui/ui/Label.mdx | 2 +- docs/docs/api/appkit-ui/ui/Menubar.mdx | 32 ++++++------- docs/docs/api/appkit-ui/ui/NavigationMenu.mdx | 16 +++---- docs/docs/api/appkit-ui/ui/Pagination.mdx | 14 +++--- docs/docs/api/appkit-ui/ui/Popover.mdx | 8 ++-- docs/docs/api/appkit-ui/ui/Progress.mdx | 2 +- docs/docs/api/appkit-ui/ui/RadioGroup.mdx | 4 +- .../docs/api/appkit-ui/ui/ResizableHandle.mdx | 6 +-- docs/docs/api/appkit-ui/ui/ScrollArea.mdx | 4 +- docs/docs/api/appkit-ui/ui/Select.mdx | 20 ++++---- docs/docs/api/appkit-ui/ui/Separator.mdx | 2 +- docs/docs/api/appkit-ui/ui/Sheet.mdx | 16 +++---- docs/docs/api/appkit-ui/ui/Sidebar.mdx | 48 +++++++++---------- docs/docs/api/appkit-ui/ui/Skeleton.mdx | 2 +- docs/docs/api/appkit-ui/ui/Slider.mdx | 2 +- docs/docs/api/appkit-ui/ui/Spinner.mdx | 2 +- docs/docs/api/appkit-ui/ui/Switch.mdx | 2 +- docs/docs/api/appkit-ui/ui/Table.mdx | 16 +++---- docs/docs/api/appkit-ui/ui/Tabs.mdx | 8 ++-- docs/docs/api/appkit-ui/ui/Textarea.mdx | 2 +- docs/docs/api/appkit-ui/ui/Toaster.mdx | 2 +- docs/docs/api/appkit-ui/ui/Toggle.mdx | 2 +- docs/docs/api/appkit-ui/ui/ToggleGroup.mdx | 4 +- docs/docs/api/appkit-ui/ui/Tooltip.mdx | 8 ++-- docs/docs/plugins/analytics.md | 2 +- tools/generate-component-mdx.test.ts | 3 ++ tools/generate-component-mdx.ts | 7 +-- 74 files changed, 298 insertions(+), 294 deletions(-) diff --git a/docs/docs/api/appkit-ui/data/AreaChart.mdx b/docs/docs/api/appkit-ui/data/AreaChart.mdx index 67d7cb472..215236f51 100644 --- a/docs/docs/api/appkit-ui/data/AreaChart.mdx +++ b/docs/docs/api/appkit-ui/data/AreaChart.mdx @@ -90,7 +90,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 3582058fe..1286acf11 100644 --- a/docs/docs/api/appkit-ui/data/BarChart.mdx +++ b/docs/docs/api/appkit-ui/data/BarChart.mdx @@ -84,7 +84,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 f30bdab3d..fdd0ce0d6 100644 --- a/docs/docs/api/appkit-ui/data/DataTable.mdx +++ b/docs/docs/api/appkit-ui/data/DataTable.mdx @@ -82,7 +82,7 @@ true/false; timestamps as `YYYY-MM-DD HH:MM:SS`; objects as JSON; null and empty ### 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 69ae163b8..edac37772 100644 --- a/docs/docs/api/appkit-ui/data/DonutChart.mdx +++ b/docs/docs/api/appkit-ui/data/DonutChart.mdx @@ -79,7 +79,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 fe81900fe..412c4c900 100644 --- a/docs/docs/api/appkit-ui/data/HeatmapChart.mdx +++ b/docs/docs/api/appkit-ui/data/HeatmapChart.mdx @@ -101,7 +101,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 4456d3d90..70d4bf2d5 100644 --- a/docs/docs/api/appkit-ui/data/LineChart.mdx +++ b/docs/docs/api/appkit-ui/data/LineChart.mdx @@ -88,7 +88,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 e675c1f1c..2546dd285 100644 --- a/docs/docs/api/appkit-ui/data/PieChart.mdx +++ b/docs/docs/api/appkit-ui/data/PieChart.mdx @@ -79,7 +79,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 58ee2bbc6..fa2361be0 100644 --- a/docs/docs/api/appkit-ui/data/RadarChart.mdx +++ b/docs/docs/api/appkit-ui/data/RadarChart.mdx @@ -82,7 +82,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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 cd87109fb..3921166db 100644 --- a/docs/docs/api/appkit-ui/data/ScatterChart.mdx +++ b/docs/docs/api/appkit-ui/data/ScatterChart.mdx @@ -84,7 +84,7 @@ Supports both query mode (queryKey + parameters) and data mode (static data). ### 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';
``` @@ -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';