From 4ed6d1488d8c70f6f05a5a354f65a3734111d336 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:34:17 +0000 Subject: [PATCH 1/6] fix(plugin-charts): a value axis prints its dataset measure's percent and currency units WIP: carrier, formatter, producers. Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- .../plugin-charts/src/AdvancedChartImpl.tsx | 22 ++- .../plugin-charts/src/ChartRenderer.tsx | 10 +- .../plugin-charts/src/normalizeChartSchema.ts | 137 +++++++++++++++++- .../plugin-dashboard/src/DatasetWidget.tsx | 47 +++++- .../src/DatasetReportRenderer.tsx | 42 +++++- 5 files changed, 240 insertions(+), 18 deletions(-) diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.tsx index e83cc8e2615..4811aff632a 100644 --- a/ui/packages/plugin-charts/src/AdvancedChartImpl.tsx +++ b/ui/packages/plugin-charts/src/AdvancedChartImpl.tsx @@ -52,7 +52,7 @@ import { ChartContainerConfig } from './ChartContainerImpl'; import { mapScatterClick, mapTreemapClick, mapSankeyClick } from './chartDrillEvents'; -import { formatterFor, compactTickFormatter, valueTickExponent, domainFor, ticksFor, plotsWholeNumbers, wholeNumberTickCount, RENDERABLE, SINGLE_VALUE_CHART_TYPES, TABULAR_CHART_TYPES, effectiveChartFamily, comboBaseFamily, placeYAxes, type DeclaredChartFamily, type NormalizedAxis, type NormalizedSeries, type ValueAxisSlot, type YAxisPlacement } from './normalizeChartSchema'; +import { formatterFor, compactTickFormatter, measureTickFormatter, sharedMeasureFormat, valueTickExponent, domainFor, ticksFor, plotsWholeNumbers, wholeNumberTickCount, RENDERABLE, SINGLE_VALUE_CHART_TYPES, TABULAR_CHART_TYPES, effectiveChartFamily, comboBaseFamily, placeYAxes, type DeclaredChartFamily, type NormalizedAxis, type NormalizedSeries, type ValueAxisSlot, type YAxisPlacement } from './normalizeChartSchema'; import { buildCategoryRank, chartRowBucketId, formatMonthBucketLabel, isRealCalendarDate, toDateInputValue, toDisplayDate, type ChartSegmentClickEvent } from '@object-ui/core'; import { createSafeTranslation, useDisplayLocale, useSafeTranslate } from '@object-ui/i18n'; @@ -2593,18 +2593,24 @@ function AdvancedChartImplInner({ /** * The tick formatter of one value axis: the author's `format` where it - * declares one, else the compact default (1,200,000 → `1.2M`) — either - * printed to the decimal place the axis' tick step needs, so two ticks never - * share a label (objectstack#36988; see `valueTickExponent`). The step is - * measured over the values plotted in the slot, with the tick count - * `yAxisSpecProps` hands recharts for it. + * declares one, else the units of the dataset measure its series plot + * (objectstack#37053: a percent at its own scale, a currency's symbol — see + * `measureTickFormatter`), else the compact default (1,200,000 → `1.2M`) — + * each printed to the decimal place the axis' tick step needs, so two ticks + * never share a label (objectstack#36988; see `valueTickExponent`). The step + * is measured over the values plotted in the slot, with the tick count + * `yAxisSpecProps` hands recharts for it. Data labels print with the same + * formatter (`valueTickFormatterOf`), so they carry the measure's units too. */ const valueAxisTickFormatter = React.useCallback( (axis: NormalizedAxis | undefined, side: ValueAxisSlot) => { + const plotted = slotSeries(side); const values = axisValues(side); - const tickCount = plotsWholeNumbers(slotSeries(side)) ? wholeNumberTickCount(axis, values) : undefined; + const tickCount = plotsWholeNumbers(plotted) ? wholeNumberTickCount(axis, values) : undefined; const exponent = valueTickExponent(axis, values, tickCount); - return formatterFor(axis?.format, displayLocale, exponent) ?? compactTickFormatter(displayLocale, exponent); + return formatterFor(axis?.format, displayLocale, exponent) + ?? measureTickFormatter(sharedMeasureFormat(plotted), displayLocale, exponent) + ?? compactTickFormatter(displayLocale, exponent); }, [axisValues, slotSeries, displayLocale], ); diff --git a/ui/packages/plugin-charts/src/ChartRenderer.tsx b/ui/packages/plugin-charts/src/ChartRenderer.tsx index e7fbb038b44..dea801d65c6 100644 --- a/ui/packages/plugin-charts/src/ChartRenderer.tsx +++ b/ui/packages/plugin-charts/src/ChartRenderer.tsx @@ -4,7 +4,7 @@ import { Skeleton } from '@object-ui/components'; import type { ChartContainerConfig } from './ChartContainerImpl'; import type { ChartSegmentClickEvent } from '@object-ui/core'; import { useObjectTranslation } from '@object-ui/i18n'; -import { normalizeChartSchema } from './normalizeChartSchema'; +import { normalizeChartSchema, type MeasureValueFormat } from './normalizeChartSchema'; // 🚀 Lazy load the implementation files const LazyChart = React.lazy(() => import('./ChartImpl')); @@ -76,9 +76,13 @@ export interface ChartRendererProps { * the measure's aggregate, carried by `buildChartSeries` from the dataset * answer, so a value axis over counts draws whole-number ticks. The * authoring face refuses it by name (`ChartDataSeriesSchema.aggregate`). + * `measureFormat` is the same kind of carrier (objectstack#37053): the + * measure's `format` / `currency` / `percentScale`, filled by a + * dataset-bound producer so the value axis prints the measure's units — + * see `NormalizedSeries.measureFormat`. */ series?: Array< - | { dataKey: string; label?: string; type?: string; variant?: 'current' | 'comparison'; opacity?: number; dashArray?: string; chartType?: 'bar' | 'line' | 'area'; stack?: string; yAxis?: 'left' | 'right'; color?: string; aggregate?: string } + | { dataKey: string; label?: string; type?: string; variant?: 'current' | 'comparison'; opacity?: number; dashArray?: string; chartType?: 'bar' | 'line' | 'area'; stack?: string; yAxis?: 'left' | 'right'; color?: string; aggregate?: string; measureFormat?: MeasureValueFormat } | { name: string; label?: unknown; type?: string; variant?: 'current' | 'comparison' | 'primary'; opacity?: number; dashArray?: string; stack?: string; yAxis?: 'left' | 'right'; color?: string } >; /** Spec `ChartConfig` shape — honored via `normalizeChartSchema` @@ -162,7 +166,7 @@ export const ChartRenderer: React.FC = ({ schema, onChartCli // `normalizeSeries` is a no-op on a well-formed internal-shaped entry apart // from `type`: it round-trips every other key the internal arm of // `ChartRendererProps.series` declares (`dataKey`/`label`/`chartType`/ - // `variant`/`opacity`/`dashArray`/`stack`/`yAxis`/`color`/`aggregate`) unchanged, and + // `variant`/`opacity`/`dashArray`/`stack`/`yAxis`/`color`/`aggregate`/`measureFormat`) unchanged, and // translates `type` to `chartType` — the translation this routing exists // for. So always taking the normalized array // is not a second read site for `type` (AGENTS.md #0.1) — it is routing diff --git a/ui/packages/plugin-charts/src/normalizeChartSchema.ts b/ui/packages/plugin-charts/src/normalizeChartSchema.ts index c84e1cacb0b..688a7da856c 100644 --- a/ui/packages/plugin-charts/src/normalizeChartSchema.ts +++ b/ui/packages/plugin-charts/src/normalizeChartSchema.ts @@ -7,7 +7,7 @@ */ import { pickLocalized } from '@object-ui/i18n'; -import { isIntegerAggregate } from '@object-ui/core'; +import { formatMeasure, isIntegerAggregate } from '@object-ui/core'; import type { ObjectChartSchema } from '@object-ui/types'; /** @@ -272,6 +272,63 @@ export interface NormalizedSeries { * so an author cannot claim integer ticks for a currency sum. */ aggregate?: string; + /** + * How the measure this series plots is formatted — renderer-internal, like + * {@link aggregate}: a dataset-bound producer (the report chart, the + * dashboard widget) fills it from the answer's `fields[]` facts, and no + * author writes it (objectstack#37053). A value axis whose series all carry + * the same one prints its ticks in the measure's units (see + * `measureTickFormatter`). + */ + measureFormat?: MeasureValueFormat; +} + +/** + * The facts a value axis needs to print a dataset measure's ticks in the + * measure's units, the way the table beside it prints the measure + * (objectstack#37053): its numeral `format` pattern, the ONE `currency` every + * cell of the column shows, and the `percentScale` its stored number is at. A + * per-row currency column (`currencyField`, ADR-0144 D9) has no single + * currency, so its producer leaves `currency` out and the axis keeps its + * plain numbers. + */ +export interface MeasureValueFormat { + format?: string; + currency?: string; + percentScale?: 'fraction' | 'whole'; +} + +/** + * Read one series' {@link MeasureValueFormat} carrier, keeping only the keys + * of its shape; `undefined` when it states none. + */ +function measureValueFormat(raw: unknown): MeasureValueFormat | undefined { + if (!isRec(raw)) return undefined; + const out: MeasureValueFormat = {}; + const format = str(raw.format); + if (format) out.format = format; + const currency = str(raw.currency); + if (currency) out.currency = currency; + if (raw.percentScale === 'fraction' || raw.percentScale === 'whole') out.percentScale = raw.percentScale; + return Object.keys(out).length > 0 ? out : undefined; +} + +/** + * The {@link MeasureValueFormat} a value axis plotting `series` prints its + * ticks with (objectstack#37053): the carrier every one of them states, when + * they all state the same one, and it names a unit the axis can print — a + * currency, or a `%` pattern. A series with none, two measures formatted + * differently, or a plain numeral pattern leave the axis on its default, the + * same all-or-nothing rule {@link plotsWholeNumbers} reads `aggregate` by. + */ +export function sharedMeasureFormat(series: readonly NormalizedSeries[]): MeasureValueFormat | undefined { + const [first] = series; + const shared = first?.measureFormat; + if (!shared) return undefined; + const same = (m: MeasureValueFormat | undefined): boolean => + m?.format === shared.format && m?.currency === shared.currency && m?.percentScale === shared.percentScale; + if (!series.every((s) => same(s.measureFormat))) return undefined; + return shared.currency || shared.format?.includes('%') ? shared : undefined; } /** @@ -505,6 +562,9 @@ function normalizeSeries(raw: unknown, language: string | null | undefined): Nor // the authoring face refuses it by name, see `NormalizedSeries.aggregate`. const aggregate = str(raw.aggregate); if (aggregate) out.aggregate = aggregate; + // Renderer-internal too (objectstack#37053), see `NormalizedSeries.measureFormat`. + const measureFormat = measureValueFormat(raw.measureFormat); + if (measureFormat) out.measureFormat = measureFormat; return out; } @@ -1000,8 +1060,14 @@ export function valueTickExponent( * (`roundingPriority: 'morePrecision'`), so no label prints fewer digits than * before; with no exponent (nothing to measure, a log scale) it is the whole * rule, as it always was. + * + * `currency` is a measure's one ISO 4217 code (objectstack#37053, see + * {@link measureTickFormatter}): the same compact number, carrying the + * locale's symbol for that currency (`CN¥1.2M`, `¥120万`). A code `Intl` + * refuses prints the plain compact number, as `formatMeasure` falls back to a + * plain number for it. */ -export function compactTickFormatter(locale: string, tickExponent?: number): (value: any) => string { +export function compactTickFormatter(locale: string, tickExponent?: number, currency?: string): (value: any) => string { return (value: any): string => { if (value == null || value === '') return ''; const num = typeof value === 'number' ? value : Number(value); @@ -1017,14 +1083,79 @@ export function compactTickFormatter(locale: string, tickExponent?: number): (va maximumFractionDigits: 1, ...(significant !== undefined ? { maximumSignificantDigits: significant, roundingPriority: 'morePrecision' } : {}), }; + // A currency's own minor-unit width (CNY 2) is the width of a cell, not + // of a compact tick: `minimumFractionDigits: 0` keeps `¥30万` from + // reading `¥30.00万`. + const money: Intl.NumberFormatOptions | undefined = currency + ? { ...opts, style: 'currency', currency, minimumFractionDigits: 0 } + : undefined; try { - return new Intl.NumberFormat(locale, opts).format(num); + return new Intl.NumberFormat(locale, money ?? opts).format(num); } catch { + if (money) { + try { + return new Intl.NumberFormat(locale, opts).format(num); + } catch { + // Fall through to the bare number, as with no currency. + } + } return String(num); } }; } +/** + * The tick formatter a value axis prints a dataset measure's ticks with — + * the measure's units on the axis, beside a table printing the same measure + * (objectstack#37053) — or `undefined` when the measure names no unit the + * axis can print, which leaves the axis on its default. + * + * `measure` is the axis' {@link sharedMeasureFormat}. Two units travel: + * + * - **A percent pattern** prints through `formatMeasure` (`@object-ui/core`), + * the function the table prints the column with, at the column's own + * `percentScale`: a `whole` column's `33.3` reads `33.3%` as it does in the + * table, which the axis' `format` key could not say — `formatterFor` reads + * a `%` pattern as a 0–1 fraction and would print `3,330%`. The pattern's + * places are a floor and grow to the axis' {@link valueTickExponent} (at + * the displayed scale: a fraction's step is 100× smaller than its points), + * the rule {@link formatterFor} applies to a declared pattern, so two ticks + * never share a label. + * - **A currency** prints the compact default with the currency's symbol + * ({@link compactTickFormatter}). Not `formatMeasure`'s full amount: that + * is the width of a cell (`CN¥1,200,000.00`), and a value axis is drawn + * 48 px wide, where the leading symbol is the part cut off. The compact + * reading is the one the axis already gives every amount. + * + * A currency wins over a percent pattern, as it does in `formatMeasure`. + */ +export function measureTickFormatter( + measure: MeasureValueFormat | undefined, + locale: string, + tickExponent?: number, +): ((value: any) => string) | undefined { + if (!measure) return undefined; + if (measure.currency) return compactTickFormatter(locale, tickExponent, measure.currency); + const format = measure.format; + if (!format?.includes('%')) return undefined; + const scale = measure.percentScale ?? 'fraction'; + // `formatMeasure`'s own count of the pattern's places. + const patternPlaces = format.split('.')[1]?.match(/0/g)?.length ?? 0; + const stepPlaces = tickExponent === undefined + ? 0 + : Math.max(0, -tickExponent - (scale === 'fraction' ? 2 : 0)); + const places = Math.min(MAX_FRACTION_DIGITS, Math.max(patternPlaces, stepPlaces)); + // The measure's pattern at the places the step needs: `formatMeasure` reads + // a pattern's places and its `%`, and groups on its own. + const pattern = `0${places > 0 ? `.${'0'.repeat(places)}` : ''}%`; + return (value: any): string => { + if (value == null || value === '') return ''; + const num = typeof value === 'number' ? value : Number(value); + if (!Number.isFinite(num)) return String(value); + return formatMeasure(num, pattern, undefined, scale, locale); + }; +} + /** * Explicit tick positions for an axis that declares a `stepSize`, or * `undefined` to keep Recharts' automatic ticks. diff --git a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx index cf7366307c5..a5d9edc16ea 100644 --- a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx +++ b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx @@ -663,6 +663,29 @@ function declaredNullCategoryLabel( return xLabel; } +/** + * The value-format facts a chart series carries for the measure it plots + * (objectstack#37053) — the chart renderer's internal `series[].measureFormat`, + * beside `aggregate`: the measure's `format` pattern, its `percentScale`, and + * the currency the table prints the column in when a cell has no row of its + * own (`measureCellCurrency` with no row). That is the one currency a value + * axis can print: a per-row currency column (`currencyField`, ADR-0144 D9) has + * none, so its axis keeps plain numbers. `undefined` when the measure states + * none of them. + */ +function measureFormatCarrier( + field: DatasetResultField | undefined, +): { format?: string; currency?: string; percentScale?: 'fraction' | 'whole' } | undefined { + if (!field) return undefined; + const currency = measureCellCurrency(field); + const carrier = { + ...(typeof field.format === 'string' && field.format !== '' ? { format: field.format } : {}), + ...(currency ? { currency } : {}), + ...(field.percentScale ? { percentScale: field.percentScale } : {}), + }; + return Object.keys(carrier).length > 0 ? carrier : undefined; +} + /** * Map a dashboard widget `type` to the advanced chart renderer's `chartType`. * Families the renderer doesn't draw distinctly fall back to their closest @@ -2382,9 +2405,31 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag // document reaches here) is handed the one measure it renders, so its other // measures are not read as groups and the dropped-measure warning above // stays true. A pivot carries one measure, so nothing is dropped from it. - const chartSeries = SINGLE_SERIES_CHART_FAMILIES.has(chartType) + const measureFilteredSeries = SINGLE_SERIES_CHART_FAMILIES.has(chartType) ? comparedChartSeries.filter((s) => !droppedMeasures.includes(s.dataKey)) : comparedChartSeries; + // objectstack#37053 — each series carries the format facts of the measure + // it plots, so the chart's value axis prints that measure's units (a + // `percentScale: 'whole'` rate reads `33.3%`, a `CNY` amount carries `¥`), + // as the flat table prints them. A pivot's series all plot its one measure; + // otherwise a series is its measure, or that measure's earlier window + // (`compareColumn`). The transposed series plots every measure, so it + // carries one only when they all format alike — the rule `aggregate` follows + // above. The chart applies a carrier only when every series on an axis + // states the same one. + const measureFormatOf = (measure: string): ReturnType => + measureFormatCarrier(measureField(measure)); + const measureAxisFormats = new Set(values.map((m) => JSON.stringify(measureFormatOf(m) ?? null))); + const seriesMeasureFormat = (dataKey: string): ReturnType => { + if (measuresOnAxis) return measureAxisFormats.size === 1 ? measureFormatOf(values[0]) : undefined; + if (pivotedSeries) return measureFormatOf(values[0]); + const measure = values.find((m) => m === dataKey || compareColumn(m) === dataKey); + return measure === undefined ? undefined : measureFormatOf(measure); + }; + const chartSeries = measureFilteredSeries.map((s) => { + const measureFormat = seriesMeasureFormat(s.dataKey); + return measureFormat ? { ...s, measureFormat } : s; + }); // Ordered-sequence charts (funnel/pyramid) need a DEFINED stage order. // `options.stageOrder` wins when the author states one explicitly; otherwise diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 6b8ca737dfa..17a5a87255e 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -2045,7 +2045,7 @@ function DatasetReportChart({ // restates the earlier window's buckets in the current window's keys, so a // month axis pairs each month with the month one period before it. const comparisonAggregate = measureField(yAxis)?.aggregate; - const drawnSeries = compareTo && !seriesBy + const comparedSeries = compareTo && !seriesBy ? [ ...chartSeries, { @@ -2056,6 +2056,17 @@ function DatasetReportChart({ }, ] : chartSeries; + // objectstack#37053 — every series plots the one measure (its `seriesBy` + // split and its earlier window included), so each carries that measure's + // format facts, and the chart's value axis prints the measure's units: a + // `percentScale: 'whole'` measure's ticks read `33.3%` beside the table's + // `33.3%`, a `CNY` amount's carry `¥`. Renderer-internal, beside + // `aggregate`; nothing authored reaches it (`mergeAuthoredSeries` lowers + // presentation keys only). + const seriesMeasureFormat = measureFormatCarrier(measureField(yAxis)); + const drawnSeries = seriesMeasureFormat + ? comparedSeries.map((s) => ({ ...s, measureFormat: seriesMeasureFormat })) + : comparedSeries; // The authored CHROME — `showLegend`, `showDataLabels`, `colors`, `subtitle`, // `description`, `annotations`, `interaction`, `height` — lowered by the same @@ -2123,6 +2134,29 @@ function DatasetReportChart({ ); } +/** + * The value-format facts a report chart's series carry for the measure they + * plot (objectstack#37053) — the chart renderer's internal + * `series[].measureFormat`: the measure's `format` pattern, its + * `percentScale`, and the currency the table prints the column in when a cell + * has no row of its own (`measureCellCurrency` with no row). That is the one + * currency a value axis can print: a per-row currency column + * (`currencyField`, ADR-0144 D9) has none, so its axis keeps plain numbers. + * `undefined` when the measure states none of them. + */ +function measureFormatCarrier( + field: DatasetResultField | undefined, +): { format?: string; currency?: string; percentScale?: 'fraction' | 'whole' } | undefined { + if (!field) return undefined; + const currency = measureCellCurrency(field); + const carrier = { + ...(typeof field.format === 'string' && field.format !== '' ? { format: field.format } : {}), + ...(currency ? { currency } : {}), + ...(field.percentScale ? { percentScale: field.percentScale } : {}), + }; + return Object.keys(carrier).length > 0 ? carrier : undefined; +} + /** * The value-axis `format` a report chart hands its chart for the measure it * plots, or `undefined` to leave the axis on the chart's own default @@ -2132,8 +2166,10 @@ function DatasetReportChart({ * the table's: the chart's axis `format` (`formatterFor`, plugin-charts) reads * a `%` pattern as a 0–1 fraction printed ×100 — `formatMeasure`'s reading at * the `fraction` scale, which is also its reading of a column the server - * leaves unannotated. Three measures keep the default instead, because that - * key cannot carry what the table prints for them: + * leaves unannotated. Three measures are handed no `format`, because that + * key cannot carry what the table prints for them; their axis reads the + * series' `measureFormat` carrier instead (objectstack#37053, see + * `measureFormatCarrier`), which a declared axis `format` would outrank: * * - `percentScale: 'whole'` — already percentage points; the axis would * multiply them by 100 a second time; From 2f93e83408396dd627d4cc50edef004231363541 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:37:47 +0000 Subject: [PATCH 2/6] test: pins for the value axis' measure units Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- ...ChartImpl.measureAxisFormat-37053.test.tsx | 186 ++++++++++++++++++ ...setWidget.measureAxisFormat-37053.test.tsx | 103 ++++++++++ ...tRenderer.measureAxisFormat-37053.test.tsx | 117 +++++++++++ 3 files changed, 406 insertions(+) create mode 100644 ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx create mode 100644 ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx create mode 100644 ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx new file mode 100644 index 00000000000..8d69112873a --- /dev/null +++ b/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx @@ -0,0 +1,186 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * objectstack#37053 — a value axis prints its dataset measure's UNITS: a + * whole-scale percent and a currency amount, beside a table that prints them + * through `formatMeasure`. + * + * The chart's value-axis `format` key is a d3-style pattern (`formatterFor`): + * it reads a `%` pattern as a 0–1 fraction and has no slot for an ISO + * currency, so a report or dashboard chart over a `percentScale: 'whole'` rate + * or a `CNY` amount printed bare numbers (`0` … `34`, `0` … `12K`) beside a + * table printing `33.3%` and `¥12,000.00`. The producer now hands each series + * the measure's `{ format, currency, percentScale }` (`series[].measureFormat`, + * renderer-internal like `series[].aggregate`), and an axis whose series all + * carry the same one prints that measure's units: + * + * - a percent pattern through `formatMeasure` itself, at the column's scale; + * - a currency as the compact default carrying the currency's symbol. + * + * A per-row currency column (`currencyField`) has no single currency, so its + * producer hands no `currency` and the axis keeps distinct plain numbers — the + * control. Every chart here is built the way `ChartRenderer` builds it: the + * schema through `normalizeChartSchema`, whose series reader is where the + * carrier is kept or dropped. + */ +import React from 'react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { render, cleanup } from '@testing-library/react'; +import { formatMeasure } from '@object-ui/core'; + +vi.mock('recharts', async () => { + const actual = await vi.importActual('recharts'); + return { + ...actual, + ResponsiveContainer: ({ children }: any) => + React.cloneElement(children, { width: 480, height: 320 }), + }; +}); + +import AdvancedChartImpl from './AdvancedChartImpl'; +import { normalizeChartSchema } from './normalizeChartSchema'; + +afterEach(cleanup); + +/** The display locale the chart resolves with no provider mounted. */ +const LOCALE = 'en'; + +const CATEGORIES = new Set(['High', 'Medium', 'Low']); + +/** The value tick labels the left axis draws, in order. */ +const valueTicks = (c: HTMLElement) => + [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] + .filter((t) => t.getAttribute('orientation') === 'left') + .map((t) => (t.textContent ?? '').trim()) + .filter((t) => !CATEGORIES.has(t)); + +/** The data labels the bars print (`showDataLabels`). */ +const dataLabels = (c: HTMLElement) => + [...c.querySelectorAll('.recharts-label-list text')].map((t) => (t.textContent ?? '').trim()); + +/** + * Draw one column chart over `rows`, its `value` series carrying `measureFormat` + * exactly as a producer hands it, through the translation `ChartRenderer` + * applies to every schema. + */ +function draw( + rows: Array<{ priority: string; value: number }>, + measureFormat: Record | undefined, + extra: Record = {}, +) { + const spec = normalizeChartSchema({ + type: 'chart', + chartType: 'column', + xAxisKey: 'priority', + series: [{ dataKey: 'value', label: 'Value', ...(measureFormat ? { measureFormat } : {}) }], + ...extra, + }); + const { container } = render( + , + ); + return container; +} + +describe('a value axis prints its dataset measure’s units (objectstack#37053)', () => { + // The SLA report's rate, stored as percentage points: one bucket at 33.3%. + const WHOLE_RATE = [ + { priority: 'High', value: 100 / 3 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + // An amount column, in thousands of yuan. + const AMOUNTS = [ + { priority: 'High', value: 12000 }, + { priority: 'Medium', value: 4500 }, + { priority: 'Low', value: 0 }, + ]; + + it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', () => { + const measure = { format: '0.0%', percentScale: 'whole' }; + const ticks = valueTicks(draw(WHOLE_RATE, measure)); + expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + // The table prints the bucket's value through `formatMeasure` at the same + // scale and pattern; each tick is that function's reading of its tick. + expect(formatMeasure(100 / 3, '0.0%', undefined, 'whole', LOCALE)).toBe('33.3%'); + expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', LOCALE))); + }); + + it('SUBJECT: a fixed-currency measure’s ticks carry its symbol', () => { + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00', currency: 'CNY' })); + expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); + // The symbol is the one the table prints the amount with. + expect(formatMeasure(12000, '0,0.00', 'CNY', undefined, LOCALE)).toBe('CN¥12,000.00'); + }); + + it('CONTROL: a per-row currency measure (no single currency) keeps distinct plain-number ticks', () => { + // A `currencyField` column's producer hands its pattern and no currency. + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00' })); + expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); + expect(new Set(ticks).size).toBe(ticks.length); + expect(ticks.some((t) => /[¥$€£%]/.test(t))).toBe(false); + }); + + it('a fraction-scale percent measure reads percents through the carrier alone (the dashboard’s case)', () => { + const rate = WHOLE_RATE.map((r) => ({ ...r, value: r.value / 100 })); + expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + }); + + it('a declared axis `format` still wins — the report’s fraction-scale `yAxis[0].format` path (objectstack#36988)', () => { + const rate = [ + { priority: 'High', value: 1 / 3 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + const ticks = valueTicks(draw(rate, { format: '0.0%' }, { yAxis: [{ format: '0.0%' }] })); + expect(ticks).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); + }); + + it('a pattern too coarse for the step gains the places the step needs, so no two ticks share a label', () => { + const rate = [ + { priority: 'High', value: 3.4 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + const ticks = valueTicks(draw(rate, { format: '0%', percentScale: 'whole' })); + expect(ticks).toEqual(['0%', '0.85%', '1.7%', '2.55%', '3.4%']); + expect(new Set(ticks).size).toBe(ticks.length); + }); + + it('data labels print with the axis’ measure format', () => { + const labels = dataLabels(draw(WHOLE_RATE, { format: '0.0%', percentScale: 'whole' }, { showDataLabels: true })); + expect(labels).toContain('33.3%'); + }); + + it('two series formatted differently on one axis keep the default axis', () => { + const spec = normalizeChartSchema({ + type: 'chart', + chartType: 'column', + xAxisKey: 'priority', + series: [ + { dataKey: 'value', measureFormat: { format: '0.0%', percentScale: 'whole' } }, + { dataKey: 'other', measureFormat: { format: '0,0.00', currency: 'CNY' } }, + ], + }); + const { container } = render( + ({ ...r, other: r.value }))} + xAxisKey="priority" + series={spec.series} + isAnimationActive={false} + />, + ); + const ticks = valueTicks(container); + expect(ticks.length).toBeGreaterThanOrEqual(3); + expect(ticks.some((t) => /[¥%]/.test(t))).toBe(false); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx new file mode 100644 index 00000000000..39da472c12a --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx @@ -0,0 +1,103 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37053 — a dashboard chart widget over a percent measure prints + * its value axis in percent, as its table prints the measure. + * + * The widget hands the chart one series per measure and, since + * `@objectstack/spec` 17.5.0, no authored axis at all (`chartConfig.yAxis` is + * refused on a widget), so nothing told the value axis what the measure's + * numbers mean: a `percentScale: 'whole'` rate of 33.3 drew bare `0` … `36` + * ticks. Each series now carries its measure's `{ format, currency, + * percentScale }` (`series[].measureFormat`, renderer-internal beside + * `aggregate`), and the axis prints that measure's units through the table's + * own `formatMeasure`. + * + * No renderer stub: the chain is `DatasetWidget` → `SchemaRenderer` → the + * registry's `chart` → `AdvancedChartImpl`, with the scoped + * `getBoundingClientRect` stub `DatasetWidget.singleSeriesMeasures-11417.test.tsx` + * uses to give the plot its box. + */ + +import { describe, it, expect, vi, afterEach, beforeAll, afterAll } from 'vitest'; +import { render, cleanup, waitFor } from '@testing-library/react'; +import { formatMeasure } from '@object-ui/core'; +// Registers `chart` in the ComponentRegistry the widget's `SchemaRenderer` +// resolves `{ type: 'chart' }` through. +import '@object-ui/plugin-charts'; +import { DatasetWidget } from '../DatasetWidget'; + +const PLOT_BOX = { width: 480, height: 320 } as const; +const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; + +beforeAll(() => { + HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) { + if (this.classList?.contains('recharts-responsive-container')) { + return { + ...PLOT_BOX, + top: 0, + left: 0, + right: PLOT_BOX.width, + bottom: PLOT_BOX.height, + x: 0, + y: 0, + toJSON() {}, + } as DOMRect; + } + return originalGetBoundingClientRect.call(this); + }; +}); + +afterAll(() => { + HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect; +}); + +afterEach(cleanup); + +const ROWS = [ + { priority: 'High', rate: 100 / 3, revenue: 12000 }, + { priority: 'Medium', rate: 0, revenue: 4500 }, + { priority: 'Low', rate: 0, revenue: 0 }, +]; +const CATEGORIES = new Set(ROWS.map((r) => r.priority)); + +/** The value tick labels the chart's left axis draws, in order. */ +const valueTicks = (c: HTMLElement) => + [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] + .filter((t) => t.getAttribute('orientation') === 'left') + .map((t) => (t.textContent ?? '').trim()) + .filter((t) => !CATEGORIES.has(t)); + +async function drawWidget(measure: string, facts: Record) { + const src = { + queryDataset: vi.fn(async () => ({ + rows: ROWS, + fields: [ + { name: 'priority', type: 'text', label: 'Priority' }, + { name: measure, type: 'number', label: 'Measure', ...facts }, + ], + })), + }; + const widget = { id: 'by_priority', type: 'bar', dataset: 'metrics', dimensions: ['priority'], values: [measure] }; + const view = render(); + await waitFor(() => expect(valueTicks(view.container).length).toBeGreaterThanOrEqual(3), { timeout: 15000 }); + return valueTicks(view.container); +} + +describe('a dashboard chart widget’s value axis prints its measure’s units (objectstack#37053)', () => { + it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', async () => { + const ticks = await drawWidget('rate', { format: '0.0%', percentScale: 'whole' }); + expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', 'en'))); + }); + + it('a fixed-currency measure’s ticks carry its symbol', async () => { + const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY' }); + expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); + }); + + it('CONTROL: a per-row currency measure keeps distinct plain-number ticks', async () => { + const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); + expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx new file mode 100644 index 00000000000..149ebae2f6c --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx @@ -0,0 +1,117 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37053 — a report chart hands its chart the measure's format + * facts, so the value axis prints the measure's units beside the table. + * + * objectstack#36988 passed a fraction-scale percent pattern on the chart's + * value-axis `format` key, and left three measures on the chart's default axis + * because that key (a d3-style pattern) cannot say what the table prints for + * them: a percent already in percentage points (`percentScale: 'whole'`), a + * declared currency, and a per-row currency (`currencyField`). Each series now + * carries the measure's `{ format, currency, percentScale }` as the chart + * renderer's internal `series[].measureFormat` (beside `aggregate`), which + * `AdvancedChartImpl.measureAxisFormat-37053.test.tsx` (plugin-charts) draws + * as `…%` and `CN¥…` ticks. The currency is the one the table prints a cell + * with no row of its own in (`measureCellCurrency`), so a per-row currency + * column hands none and its axis keeps plain numbers. + * + * This pin stops at the schema the registered chart component receives, as + * the objectstack#36988 pin in `DatasetReportRenderer.chartChrome.test.tsx` + * does: `plugin-report` does not depend on `plugin-charts`. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { ComponentRegistry } from '@object-ui/core'; +import { DatasetReportRenderer } from '../DatasetReportRenderer'; + +let captured: { schema: Record } | null = null; + +beforeEach(() => { + captured = null; + ComponentRegistry.register('chart', (props: any) => { + captured = props; + return null; + }); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const sourceOf = (result: unknown) => ({ queryDataset: vi.fn(async () => result) }); + +const ROWS = [ + { priority: 'urgent', measure: 100 / 3, currency_code: 'CNY' }, + { priority: 'high', measure: 0, currency_code: 'USD' }, + { priority: 'low', measure: 0, currency_code: 'CNY' }, +]; + +const REPORT = { + name: 'by_priority', + type: 'tabular', + dataset: 'metrics', + rows: ['priority'], + values: ['measure'], + chart: { type: 'column', xAxis: 'priority', yAxis: 'measure' }, +}; + +async function chartSchema(measure: Record, report: Record = REPORT) { + const result = { + rows: ROWS, + fields: [ + { name: 'priority', type: 'text', label: 'Priority' }, + { name: 'measure', type: 'number', label: 'Measure', ...measure }, + ], + }; + render(); + await waitFor(() => expect(captured?.schema?.data?.length).toBe(ROWS.length)); + return captured!.schema; +} + +describe('report chart series carry the measure’s format facts (objectstack#37053)', () => { + it('SUBJECT: a whole-scale percent measure hands its pattern and scale, beside the table’s 33.3%', async () => { + const schema = await chartSchema({ format: '0.0%', percentScale: 'whole' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ + { format: '0.0%', percentScale: 'whole' }, + ]); + // Still no value-axis `format`: that key would read the points as a fraction. + expect(schema).not.toHaveProperty('yAxis'); + expect(await screen.findByText('33.3%')).toBeInTheDocument(); + }); + + it('SUBJECT: a fixed-currency measure hands its currency', async () => { + const schema = await chartSchema({ format: '0,0.00', currency: 'CNY' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ + { format: '0,0.00', currency: 'CNY' }, + ]); + }); + + it('CONTROL: a per-row currency measure hands no currency — the axis has no single one', async () => { + const schema = await chartSchema({ format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([{ format: '0,0.00' }]); + }); + + it('every series of a `seriesBy` split carries the one measure’s facts', async () => { + const schema = await chartSchema( + { format: '0.0%', percentScale: 'whole' }, + { ...REPORT, rows: ['priority', 'currency_code'], chart: { ...REPORT.chart, seriesBy: 'currency_code' } }, + ); + expect(schema.series.length).toBeGreaterThanOrEqual(2); + for (const s of schema.series) expect(s.measureFormat).toEqual({ format: '0.0%', percentScale: 'whole' }); + }); + + it('a fraction-scale percent keeps its value-axis `format` (objectstack#36988) beside the carrier', async () => { + const schema = await chartSchema({ format: '0.0%' }); + expect(schema.yAxis).toEqual([{ format: '0.0%' }]); + expect(schema.series[0].measureFormat).toEqual({ format: '0.0%' }); + }); + + it('a measure stating no format facts hands no carrier', async () => { + const schema = await chartSchema({}); + expect(schema.series[0]).not.toHaveProperty('measureFormat'); + }); +}); From 1f0a3f20a129258716025800c9547442b01c1e0f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:57:40 +0000 Subject: [PATCH 3/6] chore: changesets for the value axis' measure units Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- .changeset/37053-chart-axis-measure-units.md | 15 +++++++++++++++ .../37053-dashboard-chart-measure-format.md | 12 ++++++++++++ .changeset/37053-report-chart-measure-format.md | 12 ++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 .changeset/37053-chart-axis-measure-units.md create mode 100644 .changeset/37053-dashboard-chart-measure-format.md create mode 100644 .changeset/37053-report-chart-measure-format.md diff --git a/.changeset/37053-chart-axis-measure-units.md b/.changeset/37053-chart-axis-measure-units.md new file mode 100644 index 00000000000..3ed0f4b2aa0 --- /dev/null +++ b/.changeset/37053-chart-axis-measure-units.md @@ -0,0 +1,15 @@ +--- +'@object-ui/plugin-charts': patch +--- + +fix(plugin-charts): a chart's value axis prints its dataset measure's percent and currency units + +Clause-②: yes +Metadata-protocol: none + +- **A value axis over a dataset measure reads in the measure's units.** The chart renderer's internal series props carry one more producer-filled key, `series[].measureFormat` (the measure's `format`, `currency` and `percentScale`), beside `series[].aggregate`. No author writes it. A value axis whose series all carry the same one prints its ticks, and the data labels that share its format, in that measure's units: + - a percent pattern prints through `formatMeasure`, the function the table uses, at the column's own `percentScale`. A measure stored in percentage points (`percentScale: 'whole'`) reads `0.0%` … `36.0%`, where the axis printed `0` … `36`; + - a measure with one ISO currency prints the compact default with that currency's symbol (`CN¥3K` … `CN¥12K`, `¥30万` in Chinese), where the axis printed `3K` … `12K`. +- A declared axis `format` still wins over the measure's units. A measure with a per-row currency (`currencyField`) has no single currency, so its axis keeps plain numbers. Two series on one axis that are formatted differently also keep the default axis. + +Nothing to migrate: no metadata key changes, and the widened series type is the renderer's internal one. diff --git a/.changeset/37053-dashboard-chart-measure-format.md b/.changeset/37053-dashboard-chart-measure-format.md new file mode 100644 index 00000000000..d6284b1cdda --- /dev/null +++ b/.changeset/37053-dashboard-chart-measure-format.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-dashboard': patch +--- + +fix(plugin-dashboard): a dashboard chart widget's value axis prints its measure's percent and currency units + +Clause-②: yes +Metadata-protocol: none + +A dataset chart widget's series now carry the format facts of the measure they plot (`format`, `percentScale` and its single currency) as the chart's internal `series[].measureFormat`. The value axis then prints a percent measure as percents (`0.0%` … `36.0%` for a rate in percentage points, which drew `0` … `36` before) and a currency amount with its symbol, as the widget's table prints them. A measure with a per-row currency (`currencyField`) keeps plain numbers. A dimensionless chart that plots several measures carries a format only when they all share it. + +Nothing to migrate: no metadata key changes. diff --git a/.changeset/37053-report-chart-measure-format.md b/.changeset/37053-report-chart-measure-format.md new file mode 100644 index 00000000000..4aebccb3e97 --- /dev/null +++ b/.changeset/37053-report-chart-measure-format.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-report': patch +--- + +fix(plugin-report): a report chart hands its chart the measure's format, so the value axis reads `33.3%` and `¥` beside the table + +Clause-②: yes +Metadata-protocol: none + +A report chart's series now carry the plotted measure's `format`, `percentScale` and single currency as the chart's internal `series[].measureFormat`. The chart's value axis then prints a measure stored in percentage points (`percentScale: 'whole'`) as percents and a currency amount with its symbol, as the table beside it does. A measure with a per-row currency (`currencyField`) hands no currency, so its axis keeps plain numbers. The fraction-scale percent pattern still travels on the value-axis `format` key as before. + +Nothing to migrate: no metadata key changes. From c8a011b13254a10f62f1eeda6e4dac1c5fd5b3fa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:29:20 +0000 Subject: [PATCH 4/6] test: measured tick expectations for the fraction and coarse-pattern cases Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- .../src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx index 8d69112873a..a896ad11a5e 100644 --- a/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx +++ b/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx @@ -131,7 +131,7 @@ describe('a value axis prints its dataset measure’s units (objectstack#37053)' it('a fraction-scale percent measure reads percents through the carrier alone (the dashboard’s case)', () => { const rate = WHOLE_RATE.map((r) => ({ ...r, value: r.value / 100 })); - expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); }); it('a declared axis `format` still wins — the report’s fraction-scale `yAxis[0].format` path (objectstack#36988)', () => { @@ -151,7 +151,9 @@ describe('a value axis prints its dataset measure’s units (objectstack#37053)' { priority: 'Low', value: 0 }, ]; const ticks = valueTicks(draw(rate, { format: '0%', percentScale: 'whole' })); - expect(ticks).toEqual(['0%', '0.85%', '1.7%', '2.55%', '3.4%']); + // `formatMeasure` prints a pattern's places as a fixed width, so every tick + // carries the two the 0.85-point step needs. + expect(ticks).toEqual(['0.00%', '0.85%', '1.70%', '2.55%', '3.40%']); expect(new Set(ticks).size).toBe(ticks.length); }); From 22053f07a55ca058d382b216ffbb05de87539a3d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:28:54 +0000 Subject: [PATCH 5/6] test: move the measure-unit pins into their shared harnesses; pin the two carrier copies in step Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- .../src/AdvancedChartImpl.axisLabels.test.tsx | 171 ++++++++++++++++ ...ChartImpl.measureAxisFormat-37053.test.tsx | 188 ------------------ .../plugin-dashboard/src/DatasetWidget.tsx | 8 +- ...tWidget.integerMeasureTicks-11681.test.tsx | 66 ++++++ ...setWidget.measureAxisFormat-37053.test.tsx | 103 ---------- .../src/DatasetReportRenderer.tsx | 8 +- ...DatasetReportRenderer.chartChrome.test.tsx | 92 +++++++++ ...tRenderer.measureAxisFormat-37053.test.tsx | 117 ----------- ...r.measureFormatCarrierParity-37053.test.ts | 66 ++++++ 9 files changed, 409 insertions(+), 410 deletions(-) delete mode 100644 ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx delete mode 100644 ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx delete mode 100644 ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx create mode 100644 ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx index 9699a5c5fda..576bc6e5e07 100644 --- a/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx +++ b/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, cleanup } from '@testing-library/react'; +import { formatMeasure } from '@object-ui/core'; vi.mock('recharts', async () => { const actual = await vi.importActual('recharts'); @@ -134,3 +135,173 @@ describe('AdvancedChartImpl — value-axis ticks on a small domain (objectstack# expect(ticks).toEqual(['0%', '0.85%', '1.7%', '2.55%', '3.4%']); }); }); + +/** + * objectstack#37053 — a value axis prints its dataset measure's UNITS: a + * whole-scale percent and a currency amount, beside a table that prints them + * through `formatMeasure`. + * + * The chart's value-axis `format` key is a d3-style pattern (`formatterFor`): + * it reads a `%` pattern as a 0–1 fraction and has no slot for an ISO + * currency, so a report or dashboard chart over a `percentScale: 'whole'` rate + * or a `CNY` amount printed bare numbers (`0` … `34`, `0` … `12K`) beside a + * table printing `33.3%` and `¥12,000.00`. The producer now hands each series + * the measure's `{ format, currency, percentScale }` (`series[].measureFormat`, + * renderer-internal like `series[].aggregate`), and an axis whose series all + * carry the same one prints that measure's units: + * + * - a percent pattern through `formatMeasure` itself, at the column's scale; + * - a currency as the compact default carrying the currency's symbol. + * + * A per-row currency column (`currencyField`) has no single currency, so its + * producer hands no `currency` and the axis keeps distinct plain numbers — the + * control. Every chart here is built the way `ChartRenderer` builds it: the + * schema through `normalizeChartSchema`, whose series reader is where the + * carrier is kept or dropped. + * + * A new top-level `describe` in this axis-tick harness, beside the + * objectstack#36988 one above it. + */ +describe('AdvancedChartImpl — a value axis prints its dataset measure’s units (objectstack#37053)', () => { + /** The display locale the chart resolves with no provider mounted. */ + const LOCALE = 'en'; + + const CATEGORIES = new Set(['High', 'Medium', 'Low']); + + /** The value tick labels the left axis draws, in order. */ + const valueTicks = (c: HTMLElement) => + [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] + .filter((t) => t.getAttribute('orientation') === 'left') + .map((t) => (t.textContent ?? '').trim()) + .filter((t) => !CATEGORIES.has(t)); + + /** The data labels the bars print (`showDataLabels`). */ + const dataLabels = (c: HTMLElement) => + [...c.querySelectorAll('.recharts-label-list text')].map((t) => (t.textContent ?? '').trim()); + + /** + * Draw one column chart over `rows`, its `value` series carrying `measureFormat` + * exactly as a producer hands it, through the translation `ChartRenderer` + * applies to every schema. + */ + function draw( + rows: Array<{ priority: string; value: number }>, + measureFormat: Record | undefined, + extra: Record = {}, + ) { + const spec = normalizeChartSchema({ + type: 'chart', + chartType: 'column', + xAxisKey: 'priority', + series: [{ dataKey: 'value', label: 'Value', ...(measureFormat ? { measureFormat } : {}) }], + ...extra, + }); + const { container } = render( + , + ); + return container; + } + + // The SLA report's rate, stored as percentage points: one bucket at 33.3%. + const WHOLE_RATE = [ + { priority: 'High', value: 100 / 3 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + // An amount column, in thousands of yuan. + const AMOUNTS = [ + { priority: 'High', value: 12000 }, + { priority: 'Medium', value: 4500 }, + { priority: 'Low', value: 0 }, + ]; + + it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', () => { + const measure = { format: '0.0%', percentScale: 'whole' }; + const ticks = valueTicks(draw(WHOLE_RATE, measure)); + expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + // The table prints the bucket's value through `formatMeasure` at the same + // scale and pattern; each tick is that function's reading of its tick. + expect(formatMeasure(100 / 3, '0.0%', undefined, 'whole', LOCALE)).toBe('33.3%'); + expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', LOCALE))); + }); + + it('SUBJECT: a fixed-currency measure’s ticks carry its symbol', () => { + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00', currency: 'CNY' })); + expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); + // The symbol is the one the table prints the amount with. + expect(formatMeasure(12000, '0,0.00', 'CNY', undefined, LOCALE)).toBe('CN¥12,000.00'); + }); + + it('CONTROL: a per-row currency measure (no single currency) keeps distinct plain-number ticks', () => { + // A `currencyField` column's producer hands its pattern and no currency. + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00' })); + expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); + expect(new Set(ticks).size).toBe(ticks.length); + expect(ticks.some((t) => /[¥$€£%]/.test(t))).toBe(false); + }); + + it('a fraction-scale percent measure reads percents through the carrier alone (the dashboard’s case)', () => { + const rate = WHOLE_RATE.map((r) => ({ ...r, value: r.value / 100 })); + expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); + }); + + it('a declared axis `format` still wins — the report’s fraction-scale `yAxis[0].format` path (objectstack#36988)', () => { + const rate = [ + { priority: 'High', value: 1 / 3 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + const ticks = valueTicks(draw(rate, { format: '0.0%' }, { yAxis: [{ format: '0.0%' }] })); + expect(ticks).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); + }); + + it('a pattern too coarse for the step gains the places the step needs, so no two ticks share a label', () => { + const rate = [ + { priority: 'High', value: 3.4 }, + { priority: 'Medium', value: 0 }, + { priority: 'Low', value: 0 }, + ]; + const ticks = valueTicks(draw(rate, { format: '0%', percentScale: 'whole' })); + // `formatMeasure` prints a pattern's places as a fixed width, so every tick + // carries the two the 0.85-point step needs. + expect(ticks).toEqual(['0.00%', '0.85%', '1.70%', '2.55%', '3.40%']); + expect(new Set(ticks).size).toBe(ticks.length); + }); + + it('data labels print with the axis’ measure format', () => { + const labels = dataLabels(draw(WHOLE_RATE, { format: '0.0%', percentScale: 'whole' }, { showDataLabels: true })); + expect(labels).toContain('33.3%'); + }); + + it('two series formatted differently on one axis keep the default axis', () => { + const spec = normalizeChartSchema({ + type: 'chart', + chartType: 'column', + xAxisKey: 'priority', + series: [ + { dataKey: 'value', measureFormat: { format: '0.0%', percentScale: 'whole' } }, + { dataKey: 'other', measureFormat: { format: '0,0.00', currency: 'CNY' } }, + ], + }); + const { container } = render( + ({ ...r, other: r.value }))} + xAxisKey="priority" + series={spec.series} + isAnimationActive={false} + />, + ); + const ticks = valueTicks(container); + expect(ticks.length).toBeGreaterThanOrEqual(3); + expect(ticks.some((t) => /[¥%]/.test(t))).toBe(false); + }); +}); diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx deleted file mode 100644 index a896ad11a5e..00000000000 --- a/ui/packages/plugin-charts/src/AdvancedChartImpl.measureAxisFormat-37053.test.tsx +++ /dev/null @@ -1,188 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#37053 — a value axis prints its dataset measure's UNITS: a - * whole-scale percent and a currency amount, beside a table that prints them - * through `formatMeasure`. - * - * The chart's value-axis `format` key is a d3-style pattern (`formatterFor`): - * it reads a `%` pattern as a 0–1 fraction and has no slot for an ISO - * currency, so a report or dashboard chart over a `percentScale: 'whole'` rate - * or a `CNY` amount printed bare numbers (`0` … `34`, `0` … `12K`) beside a - * table printing `33.3%` and `¥12,000.00`. The producer now hands each series - * the measure's `{ format, currency, percentScale }` (`series[].measureFormat`, - * renderer-internal like `series[].aggregate`), and an axis whose series all - * carry the same one prints that measure's units: - * - * - a percent pattern through `formatMeasure` itself, at the column's scale; - * - a currency as the compact default carrying the currency's symbol. - * - * A per-row currency column (`currencyField`) has no single currency, so its - * producer hands no `currency` and the axis keeps distinct plain numbers — the - * control. Every chart here is built the way `ChartRenderer` builds it: the - * schema through `normalizeChartSchema`, whose series reader is where the - * carrier is kept or dropped. - */ -import React from 'react'; -import { describe, it, expect, afterEach, vi } from 'vitest'; -import { render, cleanup } from '@testing-library/react'; -import { formatMeasure } from '@object-ui/core'; - -vi.mock('recharts', async () => { - const actual = await vi.importActual('recharts'); - return { - ...actual, - ResponsiveContainer: ({ children }: any) => - React.cloneElement(children, { width: 480, height: 320 }), - }; -}); - -import AdvancedChartImpl from './AdvancedChartImpl'; -import { normalizeChartSchema } from './normalizeChartSchema'; - -afterEach(cleanup); - -/** The display locale the chart resolves with no provider mounted. */ -const LOCALE = 'en'; - -const CATEGORIES = new Set(['High', 'Medium', 'Low']); - -/** The value tick labels the left axis draws, in order. */ -const valueTicks = (c: HTMLElement) => - [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] - .filter((t) => t.getAttribute('orientation') === 'left') - .map((t) => (t.textContent ?? '').trim()) - .filter((t) => !CATEGORIES.has(t)); - -/** The data labels the bars print (`showDataLabels`). */ -const dataLabels = (c: HTMLElement) => - [...c.querySelectorAll('.recharts-label-list text')].map((t) => (t.textContent ?? '').trim()); - -/** - * Draw one column chart over `rows`, its `value` series carrying `measureFormat` - * exactly as a producer hands it, through the translation `ChartRenderer` - * applies to every schema. - */ -function draw( - rows: Array<{ priority: string; value: number }>, - measureFormat: Record | undefined, - extra: Record = {}, -) { - const spec = normalizeChartSchema({ - type: 'chart', - chartType: 'column', - xAxisKey: 'priority', - series: [{ dataKey: 'value', label: 'Value', ...(measureFormat ? { measureFormat } : {}) }], - ...extra, - }); - const { container } = render( - , - ); - return container; -} - -describe('a value axis prints its dataset measure’s units (objectstack#37053)', () => { - // The SLA report's rate, stored as percentage points: one bucket at 33.3%. - const WHOLE_RATE = [ - { priority: 'High', value: 100 / 3 }, - { priority: 'Medium', value: 0 }, - { priority: 'Low', value: 0 }, - ]; - // An amount column, in thousands of yuan. - const AMOUNTS = [ - { priority: 'High', value: 12000 }, - { priority: 'Medium', value: 4500 }, - { priority: 'Low', value: 0 }, - ]; - - it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', () => { - const measure = { format: '0.0%', percentScale: 'whole' }; - const ticks = valueTicks(draw(WHOLE_RATE, measure)); - expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); - // The table prints the bucket's value through `formatMeasure` at the same - // scale and pattern; each tick is that function's reading of its tick. - expect(formatMeasure(100 / 3, '0.0%', undefined, 'whole', LOCALE)).toBe('33.3%'); - expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', LOCALE))); - }); - - it('SUBJECT: a fixed-currency measure’s ticks carry its symbol', () => { - const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00', currency: 'CNY' })); - expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); - // The symbol is the one the table prints the amount with. - expect(formatMeasure(12000, '0,0.00', 'CNY', undefined, LOCALE)).toBe('CN¥12,000.00'); - }); - - it('CONTROL: a per-row currency measure (no single currency) keeps distinct plain-number ticks', () => { - // A `currencyField` column's producer hands its pattern and no currency. - const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00' })); - expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); - expect(new Set(ticks).size).toBe(ticks.length); - expect(ticks.some((t) => /[¥$€£%]/.test(t))).toBe(false); - }); - - it('a fraction-scale percent measure reads percents through the carrier alone (the dashboard’s case)', () => { - const rate = WHOLE_RATE.map((r) => ({ ...r, value: r.value / 100 })); - expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); - }); - - it('a declared axis `format` still wins — the report’s fraction-scale `yAxis[0].format` path (objectstack#36988)', () => { - const rate = [ - { priority: 'High', value: 1 / 3 }, - { priority: 'Medium', value: 0 }, - { priority: 'Low', value: 0 }, - ]; - const ticks = valueTicks(draw(rate, { format: '0.0%' }, { yAxis: [{ format: '0.0%' }] })); - expect(ticks).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); - }); - - it('a pattern too coarse for the step gains the places the step needs, so no two ticks share a label', () => { - const rate = [ - { priority: 'High', value: 3.4 }, - { priority: 'Medium', value: 0 }, - { priority: 'Low', value: 0 }, - ]; - const ticks = valueTicks(draw(rate, { format: '0%', percentScale: 'whole' })); - // `formatMeasure` prints a pattern's places as a fixed width, so every tick - // carries the two the 0.85-point step needs. - expect(ticks).toEqual(['0.00%', '0.85%', '1.70%', '2.55%', '3.40%']); - expect(new Set(ticks).size).toBe(ticks.length); - }); - - it('data labels print with the axis’ measure format', () => { - const labels = dataLabels(draw(WHOLE_RATE, { format: '0.0%', percentScale: 'whole' }, { showDataLabels: true })); - expect(labels).toContain('33.3%'); - }); - - it('two series formatted differently on one axis keep the default axis', () => { - const spec = normalizeChartSchema({ - type: 'chart', - chartType: 'column', - xAxisKey: 'priority', - series: [ - { dataKey: 'value', measureFormat: { format: '0.0%', percentScale: 'whole' } }, - { dataKey: 'other', measureFormat: { format: '0,0.00', currency: 'CNY' } }, - ], - }); - const { container } = render( - ({ ...r, other: r.value }))} - xAxisKey="priority" - series={spec.series} - isAnimationActive={false} - />, - ); - const ticks = valueTicks(container); - expect(ticks.length).toBeGreaterThanOrEqual(3); - expect(ticks.some((t) => /[¥%]/.test(t))).toBe(false); - }); -}); diff --git a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx index a5d9edc16ea..58d4b449ab8 100644 --- a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx +++ b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx @@ -672,8 +672,14 @@ function declaredNullCategoryLabel( * axis can print: a per-row currency column (`currencyField`, ADR-0144 D9) has * none, so its axis keeps plain numbers. `undefined` when the measure states * none of them. + * + * ⚠️ A second copy of this function lives in `plugin-report`'s `DatasetReportRenderer`, because + * the shared home (`@object-ui/core`) sits outside the change that wrote it; + * `DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts` + * (plugin-report) holds the two byte-identical. Edit both, or move them to + * core together. */ -function measureFormatCarrier( +export function measureFormatCarrier( field: DatasetResultField | undefined, ): { format?: string; currency?: string; percentScale?: 'fraction' | 'whole' } | undefined { if (!field) return undefined; diff --git a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx index 536dc8fc426..01cca5dca05 100644 --- a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx +++ b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx @@ -21,6 +21,7 @@ import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'; import { render, cleanup, waitFor } from '@testing-library/react'; +import { formatMeasure } from '@object-ui/core'; // Registers `chart`, which the `SchemaRenderer` inside `DatasetWidget` // resolves. Imported at module scope so the cold transform is not billed to a // bounded test budget (AGENTS.md's flaky-test discipline, objectui#3010). @@ -150,3 +151,68 @@ describe('objectui#11681 — non-integer measures are unchanged (controls)', () await expectDecimals(c, 'a count beside a sum'); }); }); + +/** + * objectstack#37053 — a dashboard chart widget over a percent measure prints + * its value axis in percent, as its table prints the measure. + * + * The widget hands the chart one series per measure and, since + * `@objectstack/spec` 17.5.0, no authored axis at all (`chartConfig.yAxis` is + * refused on a widget), so nothing told the value axis what the measure's + * numbers mean: a `percentScale: 'whole'` rate of 33.3 drew bare `0` … `36` + * ticks. Each series now carries its measure's `{ format, currency, + * percentScale }` (`series[].measureFormat`, renderer-internal beside + * `aggregate`), and the axis prints that measure's units through the table's + * own `formatMeasure`. + * + * The chain is this file's: real end to end, the plot box stubbed. A new + * top-level `describe` in this value-axis harness, beside the `aggregate` + * carrier's pins (objectui#11681). + */ +describe('objectstack#37053 — a dashboard chart widget’s value axis prints its measure’s units', () => { + const ROWS = [ + { priority: 'High', rate: 100 / 3, revenue: 12000 }, + { priority: 'Medium', rate: 0, revenue: 4500 }, + { priority: 'Low', rate: 0, revenue: 0 }, + ]; + const PRIORITIES = new Set(ROWS.map((r) => r.priority)); + + /** The value tick labels the chart's left axis draws, in order. */ + const axisTicks = (c: HTMLElement) => + [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] + .filter((t) => t.getAttribute('orientation') === 'left') + .map((t) => (t.textContent ?? '').trim()) + .filter((t) => !PRIORITIES.has(t)); + + async function drawWidget(measure: string, facts: Record) { + const src = { + queryDataset: vi.fn(async () => ({ + rows: ROWS, + fields: [ + { name: 'priority', type: 'text', label: 'Priority' }, + { name: measure, type: 'number', label: 'Measure', ...facts }, + ], + })), + }; + const widget = { id: 'by_priority', type: 'bar', dataset: 'metrics', dimensions: ['priority'], values: [measure] }; + const view = render(); + await waitFor(() => expect(axisTicks(view.container).length).toBeGreaterThanOrEqual(3), { timeout: 15000 }); + return axisTicks(view.container); + } + + it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', async () => { + const ticks = await drawWidget('rate', { format: '0.0%', percentScale: 'whole' }); + expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', 'en'))); + }); + + it('a fixed-currency measure’s ticks carry its symbol', async () => { + const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY' }); + expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); + }); + + it('CONTROL: a per-row currency measure keeps distinct plain-number ticks', async () => { + const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); + expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx deleted file mode 100644 index 39da472c12a..00000000000 --- a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.measureAxisFormat-37053.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#37053 — a dashboard chart widget over a percent measure prints - * its value axis in percent, as its table prints the measure. - * - * The widget hands the chart one series per measure and, since - * `@objectstack/spec` 17.5.0, no authored axis at all (`chartConfig.yAxis` is - * refused on a widget), so nothing told the value axis what the measure's - * numbers mean: a `percentScale: 'whole'` rate of 33.3 drew bare `0` … `36` - * ticks. Each series now carries its measure's `{ format, currency, - * percentScale }` (`series[].measureFormat`, renderer-internal beside - * `aggregate`), and the axis prints that measure's units through the table's - * own `formatMeasure`. - * - * No renderer stub: the chain is `DatasetWidget` → `SchemaRenderer` → the - * registry's `chart` → `AdvancedChartImpl`, with the scoped - * `getBoundingClientRect` stub `DatasetWidget.singleSeriesMeasures-11417.test.tsx` - * uses to give the plot its box. - */ - -import { describe, it, expect, vi, afterEach, beforeAll, afterAll } from 'vitest'; -import { render, cleanup, waitFor } from '@testing-library/react'; -import { formatMeasure } from '@object-ui/core'; -// Registers `chart` in the ComponentRegistry the widget's `SchemaRenderer` -// resolves `{ type: 'chart' }` through. -import '@object-ui/plugin-charts'; -import { DatasetWidget } from '../DatasetWidget'; - -const PLOT_BOX = { width: 480, height: 320 } as const; -const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; - -beforeAll(() => { - HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) { - if (this.classList?.contains('recharts-responsive-container')) { - return { - ...PLOT_BOX, - top: 0, - left: 0, - right: PLOT_BOX.width, - bottom: PLOT_BOX.height, - x: 0, - y: 0, - toJSON() {}, - } as DOMRect; - } - return originalGetBoundingClientRect.call(this); - }; -}); - -afterAll(() => { - HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect; -}); - -afterEach(cleanup); - -const ROWS = [ - { priority: 'High', rate: 100 / 3, revenue: 12000 }, - { priority: 'Medium', rate: 0, revenue: 4500 }, - { priority: 'Low', rate: 0, revenue: 0 }, -]; -const CATEGORIES = new Set(ROWS.map((r) => r.priority)); - -/** The value tick labels the chart's left axis draws, in order. */ -const valueTicks = (c: HTMLElement) => - [...c.querySelectorAll('text.recharts-cartesian-axis-tick-value')] - .filter((t) => t.getAttribute('orientation') === 'left') - .map((t) => (t.textContent ?? '').trim()) - .filter((t) => !CATEGORIES.has(t)); - -async function drawWidget(measure: string, facts: Record) { - const src = { - queryDataset: vi.fn(async () => ({ - rows: ROWS, - fields: [ - { name: 'priority', type: 'text', label: 'Priority' }, - { name: measure, type: 'number', label: 'Measure', ...facts }, - ], - })), - }; - const widget = { id: 'by_priority', type: 'bar', dataset: 'metrics', dimensions: ['priority'], values: [measure] }; - const view = render(); - await waitFor(() => expect(valueTicks(view.container).length).toBeGreaterThanOrEqual(3), { timeout: 15000 }); - return valueTicks(view.container); -} - -describe('a dashboard chart widget’s value axis prints its measure’s units (objectstack#37053)', () => { - it('SUBJECT: a whole-scale percent measure’s ticks read percents, in the table’s own format', async () => { - const ticks = await drawWidget('rate', { format: '0.0%', percentScale: 'whole' }); - expect(ticks).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); - expect(ticks).toEqual([0, 9, 18, 27, 36].map((t) => formatMeasure(t, '0.0%', undefined, 'whole', 'en'))); - }); - - it('a fixed-currency measure’s ticks carry its symbol', async () => { - const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY' }); - expect(ticks).toEqual(['CN¥0', 'CN¥3K', 'CN¥6K', 'CN¥9K', 'CN¥12K']); - }); - - it('CONTROL: a per-row currency measure keeps distinct plain-number ticks', async () => { - const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); - expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); - }); -}); diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 17a5a87255e..ac70f55b249 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -2143,8 +2143,14 @@ function DatasetReportChart({ * currency a value axis can print: a per-row currency column * (`currencyField`, ADR-0144 D9) has none, so its axis keeps plain numbers. * `undefined` when the measure states none of them. + * + * ⚠️ A second copy of this function lives in `plugin-dashboard`'s `DatasetWidget`, because + * the shared home (`@object-ui/core`) sits outside the change that wrote it; + * `DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts` + * (plugin-report) holds the two byte-identical. Edit both, or move them to + * core together. */ -function measureFormatCarrier( +export function measureFormatCarrier( field: DatasetResultField | undefined, ): { format?: string; currency?: string; percentScale?: 'fraction' | 'whole' } | undefined { if (!field) return undefined; diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartChrome.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartChrome.test.tsx index 2555b8d8a5f..f6b58bede20 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartChrome.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartChrome.test.tsx @@ -355,3 +355,95 @@ describe('report chart value axis — a percent measure’s format reaches the c expect(schema).not.toHaveProperty('yAxis'); }); }); + +/** + * objectstack#37053 — a report chart hands its chart the measure's format + * facts, so the value axis prints the measure's units beside the table. + * + * objectstack#36988 passed a fraction-scale percent pattern on the chart's + * value-axis `format` key, and left three measures on the chart's default axis + * because that key (a d3-style pattern) cannot say what the table prints for + * them: a percent already in percentage points (`percentScale: 'whole'`), a + * declared currency, and a per-row currency (`currencyField`). Each series now + * carries the measure's `{ format, currency, percentScale }` as the chart + * renderer's internal `series[].measureFormat` (beside `aggregate`), which + * the objectstack#37053 describe in `AdvancedChartImpl.axisLabels.test.tsx` + * (plugin-charts) draws as `…%` and `CN¥…` ticks. The currency is the one the table prints a cell + * with no row of its own in (`measureCellCurrency`), so a per-row currency + * column hands none and its axis keeps plain numbers. + * + * This pin stops at the schema the registered chart component receives, as + * the objectstack#36988 pin above does: `plugin-report` does not depend on + * `plugin-charts`. + */ +describe('report chart series carry the measure’s format facts (objectstack#37053)', () => { + const ROWS = [ + { priority: 'urgent', measure: 100 / 3, currency_code: 'CNY' }, + { priority: 'high', measure: 0, currency_code: 'USD' }, + { priority: 'low', measure: 0, currency_code: 'CNY' }, + ]; + + const REPORT = { + name: 'by_priority', + type: 'tabular', + dataset: 'metrics', + rows: ['priority'], + values: ['measure'], + chart: { type: 'column', xAxis: 'priority', yAxis: 'measure' }, + }; + + async function chartSchema(measure: Record, report: Record = REPORT) { + const result = { + rows: ROWS, + fields: [ + { name: 'priority', type: 'text', label: 'Priority' }, + { name: 'measure', type: 'number', label: 'Measure', ...measure }, + ], + }; + render(); + await waitFor(() => expect(captured?.schema?.data?.length).toBe(ROWS.length)); + return captured!.schema; + } + + it('SUBJECT: a whole-scale percent measure hands its pattern and scale, beside the table’s 33.3%', async () => { + const schema = await chartSchema({ format: '0.0%', percentScale: 'whole' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ + { format: '0.0%', percentScale: 'whole' }, + ]); + // Still no value-axis `format`: that key would read the points as a fraction. + expect(schema).not.toHaveProperty('yAxis'); + expect(await screen.findByText('33.3%')).toBeInTheDocument(); + }); + + it('SUBJECT: a fixed-currency measure hands its currency', async () => { + const schema = await chartSchema({ format: '0,0.00', currency: 'CNY' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ + { format: '0,0.00', currency: 'CNY' }, + ]); + }); + + it('CONTROL: a per-row currency measure hands no currency — the axis has no single one', async () => { + const schema = await chartSchema({ format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); + expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([{ format: '0,0.00' }]); + }); + + it('every series of a `seriesBy` split carries the one measure’s facts', async () => { + const schema = await chartSchema( + { format: '0.0%', percentScale: 'whole' }, + { ...REPORT, rows: ['priority', 'currency_code'], chart: { ...REPORT.chart, seriesBy: 'currency_code' } }, + ); + expect(schema.series.length).toBeGreaterThanOrEqual(2); + for (const s of schema.series) expect(s.measureFormat).toEqual({ format: '0.0%', percentScale: 'whole' }); + }); + + it('a fraction-scale percent keeps its value-axis `format` (objectstack#36988) beside the carrier', async () => { + const schema = await chartSchema({ format: '0.0%' }); + expect(schema.yAxis).toEqual([{ format: '0.0%' }]); + expect(schema.series[0].measureFormat).toEqual({ format: '0.0%' }); + }); + + it('a measure stating no format facts hands no carrier', async () => { + const schema = await chartSchema({}); + expect(schema.series[0]).not.toHaveProperty('measureFormat'); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx deleted file mode 100644 index 149ebae2f6c..00000000000 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureAxisFormat-37053.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#37053 — a report chart hands its chart the measure's format - * facts, so the value axis prints the measure's units beside the table. - * - * objectstack#36988 passed a fraction-scale percent pattern on the chart's - * value-axis `format` key, and left three measures on the chart's default axis - * because that key (a d3-style pattern) cannot say what the table prints for - * them: a percent already in percentage points (`percentScale: 'whole'`), a - * declared currency, and a per-row currency (`currencyField`). Each series now - * carries the measure's `{ format, currency, percentScale }` as the chart - * renderer's internal `series[].measureFormat` (beside `aggregate`), which - * `AdvancedChartImpl.measureAxisFormat-37053.test.tsx` (plugin-charts) draws - * as `…%` and `CN¥…` ticks. The currency is the one the table prints a cell - * with no row of its own in (`measureCellCurrency`), so a per-row currency - * column hands none and its axis keeps plain numbers. - * - * This pin stops at the schema the registered chart component receives, as - * the objectstack#36988 pin in `DatasetReportRenderer.chartChrome.test.tsx` - * does: `plugin-report` does not depend on `plugin-charts`. - */ - -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { ComponentRegistry } from '@object-ui/core'; -import { DatasetReportRenderer } from '../DatasetReportRenderer'; - -let captured: { schema: Record } | null = null; - -beforeEach(() => { - captured = null; - ComponentRegistry.register('chart', (props: any) => { - captured = props; - return null; - }); -}); - -afterEach(() => { - cleanup(); - vi.restoreAllMocks(); -}); - -const sourceOf = (result: unknown) => ({ queryDataset: vi.fn(async () => result) }); - -const ROWS = [ - { priority: 'urgent', measure: 100 / 3, currency_code: 'CNY' }, - { priority: 'high', measure: 0, currency_code: 'USD' }, - { priority: 'low', measure: 0, currency_code: 'CNY' }, -]; - -const REPORT = { - name: 'by_priority', - type: 'tabular', - dataset: 'metrics', - rows: ['priority'], - values: ['measure'], - chart: { type: 'column', xAxis: 'priority', yAxis: 'measure' }, -}; - -async function chartSchema(measure: Record, report: Record = REPORT) { - const result = { - rows: ROWS, - fields: [ - { name: 'priority', type: 'text', label: 'Priority' }, - { name: 'measure', type: 'number', label: 'Measure', ...measure }, - ], - }; - render(); - await waitFor(() => expect(captured?.schema?.data?.length).toBe(ROWS.length)); - return captured!.schema; -} - -describe('report chart series carry the measure’s format facts (objectstack#37053)', () => { - it('SUBJECT: a whole-scale percent measure hands its pattern and scale, beside the table’s 33.3%', async () => { - const schema = await chartSchema({ format: '0.0%', percentScale: 'whole' }); - expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ - { format: '0.0%', percentScale: 'whole' }, - ]); - // Still no value-axis `format`: that key would read the points as a fraction. - expect(schema).not.toHaveProperty('yAxis'); - expect(await screen.findByText('33.3%')).toBeInTheDocument(); - }); - - it('SUBJECT: a fixed-currency measure hands its currency', async () => { - const schema = await chartSchema({ format: '0,0.00', currency: 'CNY' }); - expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([ - { format: '0,0.00', currency: 'CNY' }, - ]); - }); - - it('CONTROL: a per-row currency measure hands no currency — the axis has no single one', async () => { - const schema = await chartSchema({ format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); - expect(schema.series.map((s: { measureFormat?: unknown }) => s.measureFormat)).toEqual([{ format: '0,0.00' }]); - }); - - it('every series of a `seriesBy` split carries the one measure’s facts', async () => { - const schema = await chartSchema( - { format: '0.0%', percentScale: 'whole' }, - { ...REPORT, rows: ['priority', 'currency_code'], chart: { ...REPORT.chart, seriesBy: 'currency_code' } }, - ); - expect(schema.series.length).toBeGreaterThanOrEqual(2); - for (const s of schema.series) expect(s.measureFormat).toEqual({ format: '0.0%', percentScale: 'whole' }); - }); - - it('a fraction-scale percent keeps its value-axis `format` (objectstack#36988) beside the carrier', async () => { - const schema = await chartSchema({ format: '0.0%' }); - expect(schema.yAxis).toEqual([{ format: '0.0%' }]); - expect(schema.series[0].measureFormat).toEqual({ format: '0.0%' }); - }); - - it('a measure stating no format facts hands no carrier', async () => { - const schema = await chartSchema({}); - expect(schema.series[0]).not.toHaveProperty('measureFormat'); - }); -}); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts new file mode 100644 index 00000000000..a6f94acce0d --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.measureFormatCarrierParity-37053.test.ts @@ -0,0 +1,66 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37053 — the value-format carrier is written in two places, and + * this pin keeps them in step. + * + * The report chart (`DatasetReportRenderer`) and the dashboard widget + * (`plugin-dashboard`'s `DatasetWidget`) each build a chart series' + * `measureFormat` from the measure's result field with `measureFormatCarrier`. + * Its shared home would be `@object-ui/core`, beside `buildChartSeries`' own + * `aggregate` copy, which the change that wrote it could not edit, so each + * producer carries a copy. Two copies that drift would draw one measure's axis + * two ways on two surfaces. + * + * Two halves: + * - the TEXT: the dashboard's copy is byte-identical to this package's, read + * from source (this package does not depend on `plugin-dashboard`, so it + * cannot import it); + * - the BEHAVIOUR: this package's copy, over the field shapes the producers + * meet, answers the carrier the chart reads. With the text equal, the + * dashboard's copy answers the same carrier for the same field. + */ + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, it, expect } from 'vitest'; +import { measureFormatCarrier } from '../DatasetReportRenderer'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const REPORT_SOURCE = resolve(HERE, '../DatasetReportRenderer.tsx'); +const DASHBOARD_SOURCE = resolve(HERE, '../../../plugin-dashboard/src/DatasetWidget.tsx'); + +/** The `measureFormatCarrier` declaration in one source file, signature to closing brace. */ +function carrierSource(path: string): string { + const text = readFileSync(path, 'utf8'); + const start = text.indexOf('export function measureFormatCarrier('); + expect(start, `${path} declares no exported measureFormatCarrier`).toBeGreaterThanOrEqual(0); + const end = text.indexOf('\n}\n', start); + expect(end, `${path}: measureFormatCarrier has no closing brace at column 0`).toBeGreaterThan(start); + return text.slice(start, end + 2); +} + +describe('objectstack#37053 — the report and dashboard carriers stay in step', () => { + it('the dashboard widget’s copy is byte-identical to the report’s', () => { + const report = carrierSource(REPORT_SOURCE); + // A floor, so a slice that caught nothing cannot pass by comparing two empties. + expect(report).toContain('measureCellCurrency(field)'); + expect(carrierSource(DASHBOARD_SOURCE)).toBe(report); + }); + + it.each([ + ['a whole-scale percent', { name: 'm', type: 'number', format: '0.0%', percentScale: 'whole' }, { format: '0.0%', percentScale: 'whole' }], + ['a fraction-scale percent', { name: 'm', type: 'number', format: '0.0%', percentScale: 'fraction' }, { format: '0.0%', percentScale: 'fraction' }], + ['a fixed currency', { name: 'm', type: 'number', format: '0,0.00', currency: 'CNY' }, { format: '0,0.00', currency: 'CNY' }], + ['a per-row currency: no single currency', { name: 'm', type: 'number', format: '0,0.00', currency: 'CNY', currencyField: 'code' }, { format: '0,0.00' }], + ['an empty pattern is no pattern', { name: 'm', type: 'number', format: '', currency: 'USD' }, { currency: 'USD' }], + ['no facts at all', { name: 'm', type: 'number' }, undefined], + ])('%s → the carrier the chart reads', (_what, field, carrier) => { + expect(measureFormatCarrier(field as never)).toEqual(carrier); + }); + + it('no field, no carrier', () => { + expect(measureFormatCarrier(undefined)).toBeUndefined(); + }); +}); From 8816da63b903bca7bf2095311752aed100e9b80d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 05:05:47 +0000 Subject: [PATCH 6/6] test: a declared axis format that can go red, two more currency readings, and pins for the producers' transposed and comparison branches Claude-Session: https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D Co-authored-by: Claude --- .changeset/37053-chart-axis-measure-units.md | 2 +- .../src/AdvancedChartImpl.axisLabels.test.tsx | 31 ++++++++++++- ...tWidget.integerMeasureTicks-11681.test.tsx | 46 +++++++++++++++++++ ...ortRenderer.comparePrevious-36645.test.tsx | 34 +++++++++++++- 4 files changed, 108 insertions(+), 5 deletions(-) diff --git a/.changeset/37053-chart-axis-measure-units.md b/.changeset/37053-chart-axis-measure-units.md index 3ed0f4b2aa0..bab42cff591 100644 --- a/.changeset/37053-chart-axis-measure-units.md +++ b/.changeset/37053-chart-axis-measure-units.md @@ -7,7 +7,7 @@ fix(plugin-charts): a chart's value axis prints its dataset measure's percent an Clause-②: yes Metadata-protocol: none -- **A value axis over a dataset measure reads in the measure's units.** The chart renderer's internal series props carry one more producer-filled key, `series[].measureFormat` (the measure's `format`, `currency` and `percentScale`), beside `series[].aggregate`. No author writes it. A value axis whose series all carry the same one prints its ticks, and the data labels that share its format, in that measure's units: +- **A value axis over a dataset measure reads in the measure's units.** The chart renderer's internal series props carry one more producer-filled key, `series[].measureFormat` (the measure's `format`, `currency` and `percentScale`), beside `series[].aggregate`. The report chart and the dashboard widget fill it from the dataset answer; it is not meant to be authored, and objectstack#37214 refuses it on a static chart node. A value axis whose series all carry the same one prints its ticks, and the data labels that share its format, in that measure's units: - a percent pattern prints through `formatMeasure`, the function the table uses, at the column's own `percentScale`. A measure stored in percentage points (`percentScale: 'whole'`) reads `0.0%` … `36.0%`, where the axis printed `0` … `36`; - a measure with one ISO currency prints the compact default with that currency's symbol (`CN¥3K` … `CN¥12K`, `¥30万` in Chinese), where the axis printed `3K` … `12K`. - A declared axis `format` still wins over the measure's units. A measure with a per-row currency (`currencyField`) has no single currency, so its axis keeps plain numbers. Two series on one axis that are formatted differently also keep the default axis. diff --git a/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx b/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx index 576bc6e5e07..5027195dfb5 100644 --- a/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx +++ b/ui/packages/plugin-charts/src/AdvancedChartImpl.axisLabels.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, cleanup } from '@testing-library/react'; import { formatMeasure } from '@object-ui/core'; +import { LocalizationProvider } from '@object-ui/i18n'; vi.mock('recharts', async () => { const actual = await vi.importActual('recharts'); @@ -188,6 +189,7 @@ describe('AdvancedChartImpl — a value axis prints its dataset measure’s unit rows: Array<{ priority: string; value: number }>, measureFormat: Record | undefined, extra: Record = {}, + locale?: string, ) { const spec = normalizeChartSchema({ type: 'chart', @@ -206,11 +208,15 @@ describe('AdvancedChartImpl — a value axis prints its dataset measure’s unit showDataLabels={spec.showDataLabels} isAnimationActive={false} />, + // The display locale the chart reads (`useDisplayLocale`), when a case names one. + locale + ? { wrapper: ({ children }: { children: React.ReactNode }) => {children} } + : undefined, ); return container; } - // The SLA report's rate, stored as percentage points: one bucket at 33.3%. + // A rate stored in percentage points (`percentScale: 'whole'`): one bucket at 33.3%. const WHOLE_RATE = [ { priority: 'High', value: 100 / 3 }, { priority: 'Medium', value: 0 }, @@ -240,6 +246,19 @@ describe('AdvancedChartImpl — a value axis prints its dataset measure’s unit expect(formatMeasure(12000, '0,0.00', 'CNY', undefined, LOCALE)).toBe('CN¥12,000.00'); }); + it('a second currency carries its own symbol (`USD` → `$12K`)', () => { + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00', currency: 'USD' })); + expect(ticks).toEqual(['$0', '$3K', '$6K', '$9K', '$12K']); + expect(formatMeasure(12000, '0,0.00', 'USD', undefined, LOCALE)).toBe('$12,000.00'); + }); + + it('a zh-CN session reads the currency in its own compact units (`¥30万`)', () => { + const large = AMOUNTS.map((r) => ({ ...r, value: r.value * 100 })); + const ticks = valueTicks(draw(large, { format: '0,0.00', currency: 'CNY' }, {}, 'zh-CN')); + expect(ticks).toEqual(['¥0', '¥30万', '¥60万', '¥90万', '¥120万']); + expect(formatMeasure(1200000, '0,0.00', 'CNY', undefined, 'zh-CN')).toBe('¥1,200,000.00'); + }); + it('CONTROL: a per-row currency measure (no single currency) keeps distinct plain-number ticks', () => { // A `currencyField` column's producer hands its pattern and no currency. const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00' })); @@ -253,7 +272,15 @@ describe('AdvancedChartImpl — a value axis prints its dataset measure’s unit expect(valueTicks(draw(rate, { format: '0.0%' }))).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']); }); - it('a declared axis `format` still wins — the report’s fraction-scale `yAxis[0].format` path (objectstack#36988)', () => { + it('a declared axis `format` wins over the carrier: a `0,0` axis over a `CNY` measure prints no symbol', () => { + // The two readings differ here, so swapping their order in + // `valueAxisTickFormatter` turns this red. + const ticks = valueTicks(draw(AMOUNTS, { format: '0,0.00', currency: 'CNY' }, { yAxis: [{ format: '0,0' }] })); + expect(ticks).toEqual(['0', '3,000', '6,000', '9,000', '12,000']); + expect(ticks.some((t) => t.includes('CN¥'))).toBe(false); + }); + + it('the report’s fraction-scale `yAxis[0].format` path still reads percents beside its carrier (objectstack#36988)', () => { const rate = [ { priority: 'High', value: 1 / 3 }, { priority: 'Medium', value: 0 }, diff --git a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx index 01cca5dca05..53d34a99952 100644 --- a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx +++ b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.integerMeasureTicks-11681.test.tsx @@ -215,4 +215,50 @@ describe('objectstack#37053 — a dashboard chart widget’s value axis prints i const ticks = await drawWidget('revenue', { format: '0,0.00', currency: 'CNY', currencyField: 'currency_code' }); expect(ticks).toEqual(['0', '3K', '6K', '9K', '12K']); }); + + // ── The producer's other two branches (objectstack#37053) ── + const WHOLE = { format: '0.0%', percentScale: 'whole' }; + const rateField = (name: string, facts: Record) => ({ name, type: 'number', label: name, ...facts }); + const settledTicks = async (c: HTMLElement) => { + await waitFor(() => expect(axisTicks(c).length).toBeGreaterThanOrEqual(3), { timeout: 15000 }); + return axisTicks(c); + }; + + it('a dimensionless chart of two measures that format alike: the transposed series carries their shared format', async () => { + const c = await renderChart( + { id: 'rates', type: 'bar', dataset: 'metrics', values: ['rate_a', 'rate_b'] }, + [{ rate_a: 100 / 3, rate_b: 12 }], + [rateField('rate_a', WHOLE), rateField('rate_b', WHOLE)], + ); + expect(await settledTicks(c)).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + }); + + it('CONTROL: a dimensionless chart mixing a percent and a currency carries no format, so the axis keeps plain numbers', async () => { + const c = await renderChart( + { id: 'mixed', type: 'bar', dataset: 'metrics', values: ['rate_a', 'revenue'] }, + [{ rate_a: 100 / 3, revenue: 12 }], + [rateField('rate_a', WHOLE), rateField('revenue', { format: '0,0.00', currency: 'CNY' })], + ); + const ticks = await settledTicks(c); + expect(ticks.some((t) => /[%¥]/.test(t)), JSON.stringify(ticks)).toBe(false); + }); + + it('the comparison overlay (`compareColumn`) carries its measure’s format, so the axis keeps the percent', async () => { + const c = await renderChart( + { + id: 'by_priority', + type: 'bar', + dataset: 'metrics', + dimensions: ['priority'], + values: ['rate'], + filter: { created: { $gte: '2026-04-01', $lte: '2026-06-30' } }, + compareTo: { kind: 'previousYear' }, + }, + ROWS.map((r, i) => ({ priority: r.priority, rate: r.rate, rate__compare: [20, 10, 5][i] })), + [{ name: 'priority', type: 'text', label: 'Priority' }, rateField('rate', WHOLE)], + ); + // The overlay is drawn: its three non-zero bars beside the current window's one. + await waitFor(() => expect(c.querySelectorAll('.recharts-bar-rectangle').length).toBeGreaterThanOrEqual(4), { timeout: 15000 }); + expect(await settledTicks(c)).toEqual(['0.0%', '9.0%', '18.0%', '27.0%', '36.0%']); + }); }); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx index 81890bc487b..4d4995c0ea5 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.comparePrevious-36645.test.tsx @@ -61,7 +61,7 @@ afterEach(() => { * A dataset source that answers like the executor: with `compareTo` in the * selection, every row also carries `__compare`. */ -function makeSource(opts: { refuseCompare?: boolean } = {}) { +function makeSource(opts: { refuseCompare?: boolean; amountFacts?: Record } = {}) { const selections: any[] = []; return { selections, @@ -80,7 +80,7 @@ function makeSource(opts: { refuseCompare?: boolean } = {}) { ]; return { rows, - fields: [{ name: 'amount', label: 'Amount', aggregate: 'sum' }], + fields: [{ name: 'amount', label: 'Amount', aggregate: 'sum', ...opts.amountFacts }], object: 'opportunity', dimensionFields: { stage: 'stage' }, drillRawRows: rows.map((r) => ({ stage: 'stage' in r ? String(r.stage).toLowerCase() : undefined })), @@ -287,3 +287,33 @@ describe('「Compare with previous period」 on a report (objectstack-ai/objects expect(await screen.findByTestId('report-compare-previous')).toHaveTextContent('和上一期对比'); }); }); + +/** + * objectstack#37053 — the comparison series carries the measure's format facts + * too, as `series[].measureFormat`, beside its `aggregate`. The chart's value + * axis applies a carrier only when every series on it states the same one, so + * an earlier-window series without it would cost the current one its units. + */ +describe('「Compare with previous period」 keeps the measure’s format on its comparison series (objectstack#37053)', () => { + it('both periods carry the `CNY` measure’s carrier', async () => { + const src = makeSource({ amountFacts: { format: '0,0.00', currency: 'CNY' } }); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + const carriers = chartProps!.schema.series.map((s: any) => [s.dataKey, s.measureFormat]); + expect(carriers).toEqual([ + ['amount', { format: '0,0.00', currency: 'CNY' }], + ['amount__compare', { format: '0,0.00', currency: 'CNY' }], + ]); + }); + + it('CONTROL: a measure that states no format facts gives neither series a carrier', async () => { + const src = makeSource(); + renderReport({ ...BASE, chart: { type: 'bar', xAxis: 'stage', yAxis: 'amount' } }, src); + await waitFor(() => expect(chartProps?.schema?.series).toBeDefined()); + fireEvent.click(compareSwitch()); + await waitFor(() => expect(chartProps!.schema.series).toHaveLength(2)); + for (const s of chartProps!.schema.series) expect(s).not.toHaveProperty('measureFormat'); + }); +});