Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/36988-report-chart-axis-format.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/plugin-report': patch
'@object-ui/plugin-charts': patch
---

fix(plugin-report): a report chart's value axis reads a percent measure in percent, and two value-axis ticks never share a label

Clause-②: no
Metadata-protocol: none

- **A report chart over a percent measure labels its value axis in percent.** A dataset measure with a percent `format` (`'0.0%'`) charted in a report drew its value axis in raw fractions (`0`, `0.1`, `0.2`, `0.3`) while the table beside it printed `33.3%`. The report now hands the measure's pattern to the chart as its value-axis `format`, so the axis reads `0.0%` … `34.0%`. This applies to a percent pattern on a measure stored as a 0–1 fraction, which is the table's reading of such a pattern. A measure already in percentage points (`percentScale: 'whole'`), a currency measure, and a plain numeral pattern keep the chart's default axis: the chart's axis `format` cannot say what the table prints for the first two, and a fixed-width numeral pattern (`'0,0.00'`) would outgrow the axis band where the compact default reads the same number.
- **Two ticks on a value axis never share a label.** With no axis `format`, the value axis printed at most one fraction digit, so the ticks of a small domain collapsed: a 0–⅓ axis read `0, 0.1, 0.2, 0.3, 0.3`. Each value axis now prints its ticks to the decimal place its tick step needs (`0, 0.085, 0.17, 0.255, 0.34`), in compact notation as before. A declared axis `format` keeps its own places unless they are too coarse for the step, in which case the ticks gain the places the step needs (`'0%'` over a 0.85-point step reads `0.85%`, not two `3%` ticks). Data labels follow their value axis, as they already did.

Nothing to migrate: no metadata key changes and no export changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ vi.mock('recharts', async () => {
});

import AdvancedChartImpl from './AdvancedChartImpl';
import { normalizeChartSchema } from './normalizeChartSchema';

afterEach(cleanup);

Expand Down Expand Up @@ -62,3 +63,74 @@ describe('AdvancedChartImpl — axis tick label resolution', () => {
expect(container.textContent).toMatch(/active/);
});
});

/**
* objectstack#36988 — the VALUE axis: two ticks never share a label.
*
* The card's data: one bucket at 1/3, the rest 0. recharts lays five ticks over
* that domain at a 0.085 step (0, 0.085, 0.17, 0.255, 0.34), and the compact
* fallback, capped at one fraction digit, printed them `0, 0.1, 0.2, 0.3, 0.3`
* — two ticks with one label, which no reader can tell apart. The fallback now
* prints as many digits as the axis' tick step needs, so distinct tick values
* read as distinct labels; with a declared percent `format` (what the report
* hands a `'0.0%'` measure's chart) the same ticks read as percents.
*/
describe('AdvancedChartImpl — value-axis ticks on a small domain (objectstack#36988)', () => {
const RATE = [
{ priority: 'High', rate: 1 / 3 },
{ priority: 'Medium', rate: 0 },
{ priority: 'Low', rate: 0 },
];
const PRIORITIES = new Set(RATE.map((r) => r.priority));

/** 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) => !PRIORITIES.has(t));

function draw(extra: Record<string, unknown> = {}, data: Record<string, unknown>[] = RATE) {
const { container } = render(
<AdvancedChartImpl
chartType="column"
data={data}
xAxisKey="priority"
series={[{ dataKey: 'rate', label: 'Rate' }]}
isAnimationActive={false}
{...extra}
/>,
);
return valueTicks(container);
}

it('with no axis format, every tick reads a label of its own', () => {
const ticks = draw();
// At least three drawn, so an empty or collapsed axis cannot pass.
expect(ticks.length).toBeGreaterThanOrEqual(3);
expect(new Set(ticks).size).toBe(ticks.length);
expect(ticks).toEqual(['0', '0.085', '0.17', '0.255', '0.34']);
});

it('with a declared percent format, the ticks read as percents', () => {
// The value-axis key exactly as a report hands it for a `'0.0%'` measure
// (`DatasetReportRenderer.chartChrome.test.tsx`), through the translation
// `ChartRenderer` applies.
const { yAxes } = normalizeChartSchema({ type: 'chart', yAxis: [{ format: '0.0%' }] }, 'en');
const ticks = draw({ yAxes });
expect(ticks.length).toBeGreaterThanOrEqual(3);
expect(new Set(ticks).size).toBe(ticks.length);
expect(ticks.every((t) => t.endsWith('%'))).toBe(true);
expect(ticks).toEqual(['0.0%', '8.5%', '17.0%', '25.5%', '34.0%']);
});

it('a declared format too coarse for the step still keeps the ticks apart', () => {
// A tenth of the card's rate: ticks 0, 0.0085, 0.017, 0.0255, 0.034. A
// whole-percent `'0%'` printed the last two as `3%`; the 0.85-point step
// needs two more places, which the pattern's own (none) do not cut.
const ticks = draw({ yAxes: [{ format: '0%' }] }, RATE.map((r) => ({ ...r, rate: r.rate / 10 })));
expect(ticks.length).toBeGreaterThanOrEqual(3);
expect(new Set(ticks).size).toBe(ticks.length);
expect(ticks).toEqual(['0%', '0.85%', '1.7%', '2.55%', '3.4%']);
});
});
72 changes: 38 additions & 34 deletions ui/packages/plugin-charts/src/AdvancedChartImpl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import {
ChartContainerConfig
} from './ChartContainerImpl';
import { mapScatterClick, mapTreemapClick, mapSankeyClick } from './chartDrillEvents';
import { formatterFor, 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, 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';

Expand Down Expand Up @@ -2468,19 +2468,6 @@ function AdvancedChartImplInner({
const getPalette = (): string[] =>
Array.isArray(colors) && colors.length > 0 ? colors : THEME_CHART_PALETTE;

// Compact numeric formatter for Y-axis ticks (1,200,000 → 1.2M).
// Keeps the axis readable when bar/area series have large values.
const formatYTick = React.useCallback((value: any): string => {
if (value == null || value === '') return '';
const num = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(num)) return String(value);
try {
return new Intl.NumberFormat(displayLocale, { notation: 'compact', maximumFractionDigits: 1 }).format(num);
} catch {
return String(num);
}
}, [displayLocale]);

// ── Spec ChartAxis presentation (objectui#2880 S2) ──────────────────────
// The author's `format` wins over the compact default; `min`/`max` pin the
// domain; `logarithmic` swaps the scale; `title` labels the axis. All three
Expand Down Expand Up @@ -2583,26 +2570,6 @@ function AdvancedChartImplInner({
const rotatedXAxisBand = rotateXLabels
? rotatedXAxisHeight(data.map((d) => String(xAxisTickFormatter(d?.[xAxisKey]) ?? '')))
: undefined;
const yTickFormatter = React.useMemo(
() => formatterFor(primaryY?.format, displayLocale) ?? formatYTick,
[primaryY?.format, displayLocale, formatYTick],
);
// Per slot, for the charts that draw both value axes.
const leftYTickFormatter = React.useMemo(
() => formatterFor(leftY?.format, displayLocale) ?? formatYTick,
[leftY?.format, displayLocale, formatYTick],
);
const rightYTickFormatter = React.useMemo(
() => formatterFor(rightY?.format, displayLocale) ?? formatYTick,
[rightY?.format, displayLocale, formatYTick],
);
/**
* The tick formatter of the value axis a series' marks are measured
* against — the one its value labels print with (objectstack#27372).
*/
const valueTickFormatterOf = (s: { yAxis?: string }): typeof yTickFormatter =>
hasDualAxis ? (s.yAxis === 'right' ? rightYTickFormatter : leftYTickFormatter) : yTickFormatter;

/**
* Every number plotted in one slot of a dual axis (or on the only axis,
* whichever slot it sits in) — the range `stepSize` lays its ticks over.
Expand All @@ -2624,6 +2591,43 @@ function AdvancedChartImplInner({
return out;
}, [data, slotSeries]);

/**
* 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.
*/
const valueAxisTickFormatter = React.useCallback(
(axis: NormalizedAxis | undefined, side: ValueAxisSlot) => {
const values = axisValues(side);
const tickCount = plotsWholeNumbers(slotSeries(side)) ? wholeNumberTickCount(axis, values) : undefined;
const exponent = valueTickExponent(axis, values, tickCount);
return formatterFor(axis?.format, displayLocale, exponent) ?? compactTickFormatter(displayLocale, exponent);
},
[axisValues, slotSeries, displayLocale],
);
const yTickFormatter = React.useMemo(
() => valueAxisTickFormatter(primaryY, soleYSlot),
[valueAxisTickFormatter, primaryY, soleYSlot],
);
// Per slot, for the charts that draw both value axes.
const leftYTickFormatter = React.useMemo(
() => valueAxisTickFormatter(leftY, 'left'),
[valueAxisTickFormatter, leftY],
);
const rightYTickFormatter = React.useMemo(
() => valueAxisTickFormatter(rightY, 'right'),
[valueAxisTickFormatter, rightY],
);
/**
* The tick formatter of the value axis a series' marks are measured
* against — the one its value labels print with (objectstack#27372).
*/
const valueTickFormatterOf = (s: { yAxis?: string }): typeof yTickFormatter =>
hasDualAxis ? (s.yAxis === 'right' ? rightYTickFormatter : leftYTickFormatter) : yTickFormatter;

/**
* Recharts props derived from one spec y-axis (domain / scale / ticks /
* label). The title is laid out for an axis running up the plot on the
Expand Down
107 changes: 105 additions & 2 deletions ui/packages/plugin-charts/src/normalizeChartSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,8 +888,20 @@ export function effectiveChartFamily<T extends DeclaredChartFamily | undefined>(
* `undefined` — the MACHINE's locale, neither of the repo's two locale
* channels (objectui#9909). A required parameter is the one shape a caller
* cannot forget.
*
* `tickExponent` is a value axis' {@link valueTickExponent}: the decimal place
* its ticks must print to for no two of them to share a label
* (objectstack#36988). The pattern's own places are a floor, never cut: a
* `'0.0%'` axis whose ticks fall on whole tenths of a percent prints exactly
* as authored, and only a pattern too coarse for the step (`'0%'` over a
* 0.85-point step) prints the further digits the step needs. Omitted (the
* category axis, scatter's measure axis), the pattern alone decides.
*/
export function formatterFor(format: string | undefined, locale: string): ((value: any) => string) | undefined {
export function formatterFor(
format: string | undefined,
locale: string,
tickExponent?: number,
): ((value: any) => string) | undefined {
if (!format) return undefined;
const isPercent = format.includes('%');
const currencyMatch = /^([$£€¥₹])/.exec(format);
Expand All @@ -901,9 +913,12 @@ export function formatterFor(format: string | undefined, locale: string): ((valu
// Nothing recognizable to act on — don't guess.
if (!isPercent && !currencyMatch && !grouped && decimals === 0) return undefined;

// `style: 'percent'` prints the value × 100, so a percent axis needs two
// places fewer than the fraction it plots.
const stepPlaces = tickExponent === undefined ? 0 : Math.max(0, -tickExponent - (isPercent ? 2 : 0));
const opts: Intl.NumberFormatOptions = {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
maximumFractionDigits: Math.min(MAX_FRACTION_DIGITS, Math.max(decimals, stepPlaces)),
useGrouping: grouped,
};
if (isPercent) opts.style = 'percent';
Expand All @@ -922,6 +937,94 @@ export function formatterFor(format: string | undefined, locale: string): ((valu
};
}

/** `Intl.NumberFormat`'s ceiling on fraction and significant digits. */
const MAX_FRACTION_DIGITS = 20;
const MAX_SIGNIFICANT_DIGITS = 21;

/** The power of ten `n` sits at (`0.085` → -2, `1000` → 3), read exactly. */
function decimalExponent(n: number): number {
return Number(Math.abs(n).toExponential().split('e')[1]);
}

/**
* The decimal place, as a power-of-ten exponent, a value axis prints its ticks
* to so that no two ticks share a label (objectstack#36988) — `-3` means
* thousandths. `undefined` when the axis gives nothing to measure (no finite
* value, an empty span) or draws a logarithmic scale, whose ticks are not
* evenly stepped; the caller then keeps its default digits.
*
* recharts lays `tickCount` ticks over the axis domain at a "nice" step that
* is never smaller than `span / (tickCount - 1)` and carries at most two
* significant digits (a multiple of 0.05 of its power of ten: 0.085, 0.45,
* 2.5). So the place one below that lower bound's leading digit resolves every
* nice step exactly — 0.085 prints `0.085`, not `0.09` — and, because any two
* ticks are at least one step apart, rounding both to that place can never
* land them on one label. A declared `stepSize` IS the step.
*
* The span is the one {@link ticksFor} lays a declared step over: the axis'
* own `min`/`max` where declared, else the plotted values with zero included
* (recharts' default value domain is `[0, 'auto']`). Every way the real
* domain differs from it — a stack summing higher, data overflowing a
* declared end — only widens the real step, which needs no extra digit.
* `tickCount` defaults to recharts' own five.
*/
export function valueTickExponent(
axis: NormalizedAxis | undefined,
values: readonly number[],
tickCount: number = RECHARTS_DEFAULT_TICK_COUNT,
): number | undefined {
if (axis?.logarithmic) return undefined;
let step = axis?.stepSize;
if (step === undefined) {
const finite = values.filter((v) => Number.isFinite(v));
if (finite.length === 0) return undefined;
const lo = axis?.min ?? Math.min(0, ...finite);
const hi = axis?.max ?? Math.max(0, ...finite);
step = (hi - lo) / Math.max(1, tickCount - 1);
}
if (!Number.isFinite(step) || step <= 0) return undefined;
return decimalExponent(step) - 1;
}

/**
* The value axis' default tick formatter — compact notation (1,200,000 →
* `1.2M`) for an axis that declares no `format`, keeping large magnitudes
* readable — printed to the axis' {@link valueTickExponent}.
*
* Compact notation alone, capped at one fraction digit, printed the ticks of
* a 0–⅓ axis (0, 0.085, 0.17, 0.255, 0.34) as `0, 0.1, 0.2, 0.3, 0.3`: two
* ticks, one label (objectstack#36988). Each value is now rounded to the
* axis' tick place instead, expressed as SIGNIFICANT digits so that the
* compact unit — `K`/`M` in English, `万`/`亿` in Chinese — never changes which
* place is kept. The one-fraction-digit reading stays a floor
* (`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.
*/
export function compactTickFormatter(locale: string, tickExponent?: number): (value: any) => string {
return (value: any): string => {
if (value == null || value === '') return '';
const num = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(num)) return String(value);
const significant = tickExponent === undefined || num === 0
? undefined
: Math.min(MAX_SIGNIFICANT_DIGITS, Math.max(1, decimalExponent(num) - tickExponent + 1));
// `roundingPriority` is ES2023 `Intl`; this package's lib is ES2020, hence
// the widened type. An engine without it reads the significant digits
// alone, which still keep every tick apart.
const opts: Intl.NumberFormatOptions & { roundingPriority?: 'morePrecision' } = {
notation: 'compact',
maximumFractionDigits: 1,
...(significant !== undefined ? { maximumSignificantDigits: significant, roundingPriority: 'morePrecision' } : {}),
};
try {
return new Intl.NumberFormat(locale, opts).format(num);
} catch {
return String(num);
}
};
}

/**
* Explicit tick positions for an axis that declares a `stepSize`, or
* `undefined` to keep Recharts' automatic ticks.
Expand Down
Loading
Loading