Skip to content

Commit bf55619

Browse files
committed
fix(ag-grid-table): apply small number format to grid cells
The AG Grid Table painted cells through valueFormatter(), which used col.formatter(value) and never read col.config.d3SmallNumberFormat, so a column with a small number format rendered 0.1 as 0.10 while the classic Table rendered 10.00%. Mirror formatColumnValue's small-number branch in valueFormatter, and drop the backend report path's AG Grid exception in client_processing.table() so an emailed report matches the chart.
1 parent 7819e82 commit bf55619

4 files changed

Lines changed: 132 additions & 33 deletions

File tree

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/**
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
import { GenericDataType } from '@apache-superset/core/common';
20+
import { CurrencyFormatter, getNumberFormatter } from '@superset-ui/core';
21+
import { ValueFormatterParams } from '@superset-ui/core/components/ThemedAgGridReact';
22+
import { DataColumnMeta } from '@superset-ui/chart-controls';
23+
import { formatColumnValue, valueFormatter } from './formatValue';
24+
import { InputColumn } from '../types';
25+
26+
const makeColumn = (overrides: Partial<InputColumn> = {}): InputColumn =>
27+
({
28+
key: 'metric',
29+
label: 'metric',
30+
dataType: GenericDataType.Numeric,
31+
isNumeric: true,
32+
isMetric: true,
33+
isPercentMetric: false,
34+
config: { d3SmallNumberFormat: '.2%' },
35+
formatter: getNumberFormatter(',.2f'),
36+
...overrides,
37+
}) as InputColumn;
38+
39+
const makeParams = (value: unknown): ValueFormatterParams =>
40+
({
41+
value,
42+
data: { metric: value },
43+
}) as unknown as ValueFormatterParams;
44+
45+
test('valueFormatter applies the small number format to values below one', () => {
46+
expect(valueFormatter(makeParams(0.1), makeColumn())).toBe('10.00%');
47+
});
48+
49+
test('valueFormatter keeps the plain number format for values of one or more', () => {
50+
expect(valueFormatter(makeParams(1234.56), makeColumn())).toBe('1,234.56');
51+
});
52+
53+
test('valueFormatter falls back to the plain formatter when no small number format is set', () => {
54+
const noSmallFormat = makeColumn({ config: {} });
55+
expect(valueFormatter(makeParams(0.1), noSmallFormat)).toBe('0.10');
56+
const emptySmallFormat = makeColumn({
57+
config: { d3SmallNumberFormat: '' },
58+
});
59+
expect(valueFormatter(makeParams(0.1), emptySmallFormat)).toBe('0.10');
60+
const nullSmallFormat = makeColumn({
61+
config: { d3SmallNumberFormat: null },
62+
});
63+
expect(valueFormatter(makeParams(0.1), nullSmallFormat)).toBe('0.10');
64+
});
65+
66+
test('valueFormatter applies the small number format to negative small values', () => {
67+
expect(valueFormatter(makeParams(-0.1), makeColumn())).toBe('-10.00%');
68+
});
69+
70+
test('valueFormatter matches formatColumnValue for small numbers', () => {
71+
const column = makeColumn();
72+
expect(formatColumnValue(column as unknown as DataColumnMeta, 0.1)[1]).toBe(
73+
'10.00%',
74+
);
75+
expect(valueFormatter(makeParams(0.1), column)).toBe('10.00%');
76+
});
77+
78+
test('valueFormatter applies the small number format to currency columns', () => {
79+
const currencyColumn = makeColumn({
80+
formatter: new CurrencyFormatter({
81+
d3Format: '$,.2f',
82+
currency: { symbol: 'USD', symbolPosition: 'prefix' },
83+
}),
84+
config: {
85+
d3SmallNumberFormat: '.2%',
86+
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
87+
},
88+
});
89+
expect(
90+
formatColumnValue(currencyColumn as unknown as DataColumnMeta, 0.1)[1],
91+
).toBe('$ 10.00');
92+
expect(valueFormatter(makeParams(0.1), currencyColumn)).toBe('$ 10.00');
93+
});

‎superset-frontend/plugins/plugin-chart-ag-grid-table/src/utils/formatValue.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,18 +101,32 @@ export const valueFormatter = (
101101
value !== '' &&
102102
!(value instanceof DateWithFormatter && isEmptyDateInput(value.input))
103103
) {
104+
// Mirror formatColumnValue: small numbers (|value| < 1) in numeric
105+
// columns use the column's small number format when one is set, so grid
106+
// cells match the drill-to-detail display instead of the plain number
107+
// format. A null/empty d3SmallNumberFormat falls back to the plain
108+
// formatter (getSmallNumberFormatter returns it unchanged).
109+
const isSmallNumber =
110+
col.dataType === GenericDataType.Numeric &&
111+
typeof value === 'number' &&
112+
Math.abs(value) < 1;
113+
const formatter = isSmallNumber
114+
? getSmallNumberFormatter(
115+
col.formatter,
116+
col.config?.d3SmallNumberFormat,
117+
col.config?.currencyFormat,
118+
)
119+
: col.formatter;
104120
// Fall back to String(value) rather than the raw value: value can be a
105121
// DateWithFormatter/Date (or other object) when col.formatter is unset or
106122
// returns a falsy result, and returning that raw object here - though it
107123
// satisfies this function's `: string` signature at compile time since
108124
// `value`'s param type is loosely typed - crashes React with "Objects are
109125
// not valid as a React child" once a cell renderer renders it directly.
110-
if (col.formatter instanceof CurrencyFormatter) {
111-
return (
112-
col.formatter(value, data, col.currencyCodeColumn) || String(value)
113-
);
126+
if (formatter instanceof CurrencyFormatter) {
127+
return formatter(value, data, col.currencyCodeColumn) || String(value);
114128
}
115-
return col.formatter?.(value) || String(value);
129+
return formatter?.(value) || String(value);
116130
}
117131
if (node?.level === -1) {
118132
return '';

‎superset/charts/client_processing.py‎

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,17 +1009,13 @@ def is_small_number(value: Any) -> bool:
10091009
return abs(float(value)) < 1
10101010

10111011

1012-
def configured_small_number_format(
1013-
config: dict[str, Any], applies: bool
1014-
) -> Optional[str]:
1012+
def configured_small_number_format(config: dict[str, Any]) -> Optional[str]:
10151013
"""
10161014
The small-number format a column config sets, or ``None``.
10171015
1018-
``applies`` is false for a chart that ignores the format. A cleared Select
1019-
leaves a blank string behind, which the browser treats as unset.
1016+
A cleared Select leaves a blank string behind, which the browser treats
1017+
as unset.
10201018
"""
1021-
if not applies:
1022-
return None
10231019
return (config.get("d3SmallNumberFormat") or "").strip() or None
10241020

10251021

@@ -1819,12 +1815,9 @@ def table(
18191815
df[currency_column].map(currency_context_value) if currency_column else None
18201816
)
18211817
column_config = form_data.get("column_config") or {}
1822-
# ``ColumnConfigControl`` offers the small-number format for both plugins,
1823-
# but the AG Grid table's cells are painted through ``valueFormatter``,
1824-
# which formats with the column's own formatter and never builds the
1825-
# small-number one the way ``formatColumnValue`` does. A report leaves that
1826-
# format alone rather than apply one the chart itself ignores.
1827-
applies_small_number_format = form_data.get("viz_type") != AG_GRID_TABLE
1818+
# ``ColumnConfigControl`` offers the small-number format for both table
1819+
# plugins, and both paint it for cells below one, so a report applies it
1820+
# the same way rather than leaving the format alone.
18281821

18291822
def label_of(name: str) -> str:
18301823
"""Return the column label as it appears in ``df`` (verbose-renamed)."""
@@ -1926,9 +1919,7 @@ def label_of(name: str) -> str:
19261919
detected_currency,
19271920
row_currency_context,
19281921
fallback_to_detected=False,
1929-
small_d3_format=configured_small_number_format(
1930-
own_config, applies_small_number_format
1931-
),
1922+
small_d3_format=configured_small_number_format(own_config),
19321923
small_currency=own_config.get("currencyFormat"),
19331924
)
19341925
continue
@@ -1975,9 +1966,7 @@ def label_of(name: str) -> str:
19751966
# The small-number format has no dataset-level counterpart, and the
19761967
# browser pairs it with the column config's own currency rather than
19771968
# the resolved one, so both come straight from ``config``.
1978-
small_number_format = configured_small_number_format(
1979-
config, applies_small_number_format
1980-
)
1969+
small_number_format = configured_small_number_format(config)
19811970

19821971
is_number = pd.api.types.is_numeric_dtype(df[column])
19831972

‎tests/unit_tests/charts/test_client_processing.py‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4092,11 +4092,12 @@ def test_table_small_number_format_ignores_a_saved_currency() -> None:
40924092
assert formatted["amount"].tolist() == ["50.0%", "$ 12.50"]
40934093

40944094

4095-
def test_ag_grid_table_ignores_a_small_number_format() -> None:
4095+
def test_ag_grid_table_applies_a_small_number_format() -> None:
40964096
"""
4097-
The AG Grid table paints its cells through ``valueFormatter``, which never
4098-
builds the small-number formatter, so a report on one keeps the column's
4099-
normal format for every cell.
4097+
The AG Grid table paints its cells through ``valueFormatter``, which
4098+
builds the small-number formatter the way ``formatColumnValue`` does,
4099+
so a report on one applies the column's small-number format to cells
4100+
below one, exactly like the classic Table.
41004101
"""
41014102
df = pd.DataFrame.from_dict({"amount": {0: 0.5, 1: 12.5}})
41024103
column_config = {
@@ -4116,7 +4117,7 @@ def test_ag_grid_table_ignores_a_small_number_format() -> None:
41164117
{"viz_type": "table", "metrics": ["amount"], "column_config": column_config},
41174118
)
41184119

4119-
assert ag_grid["amount"].tolist() == ["0.50", "12.50"]
4120+
assert ag_grid["amount"].tolist() == ["50.0%", "12.50"]
41204121
assert plain["amount"].tolist() == ["50.0%", "12.50"]
41214122

41224123

@@ -4758,8 +4759,8 @@ def test_table_derived_column_takes_its_own_small_number_format() -> None:
47584759
`processComparisonColumns` gives each of the four its own config, and
47594760
`formatColumnValue` uses that config's `d3SmallNumberFormat` for a cell
47604761
below one. The parent metric's small-number format does not reach them,
4761-
and a blank one is unset. The AG Grid table ignores the format for these
4762-
columns as it does for any other.
4762+
and a blank one is unset. Both table viz types apply the format, since
4763+
the AG Grid table's `valueFormatter` builds it the same way.
47634764
"""
47644765
df = pd.DataFrame({"m": [110, 0.5], "m__P1D": [100, 0.25]})
47654766
column_config = {
@@ -4779,8 +4780,10 @@ def test_table_derived_column_takes_its_own_small_number_format() -> None:
47794780
assert formatted["# m"].tolist() == ["100", "0.25"]
47804781
assert formatted["△ m"].tolist() == ["10", "0.25"]
47814782
assert formatted["% m"].tolist() == ["0.10", "100.000%"]
4782-
assert ag_grid["Main m"].tolist() == ["110", "0.5"]
4783-
assert ag_grid["% m"].tolist() == ["10.000%", "100.000%"]
4783+
assert ag_grid["Main m"].tolist() == ["110", "50.0%"]
4784+
assert ag_grid["# m"].tolist() == ["100", "0.25"]
4785+
assert ag_grid["△ m"].tolist() == ["10", "0.25"]
4786+
assert ag_grid["% m"].tolist() == ["0.10", "100.000%"]
47844787

47854788

47864789
def test_table_derived_small_number_format_uses_its_own_currency() -> None:

0 commit comments

Comments
 (0)