Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { GenericDataType } from '@apache-superset/core/common';
import { CurrencyFormatter, getNumberFormatter } from '@superset-ui/core';
import { ValueFormatterParams } from '@superset-ui/core/components/ThemedAgGridReact';
import { DataColumnMeta } from '@superset-ui/chart-controls';
import { formatColumnValue, valueFormatter } from './formatValue';
import { InputColumn } from '../types';

const makeColumn = (overrides: Partial<InputColumn> = {}): InputColumn =>
({
key: 'metric',
label: 'metric',
dataType: GenericDataType.Numeric,
isNumeric: true,
isMetric: true,
isPercentMetric: false,
config: { d3SmallNumberFormat: '.2%' },
formatter: getNumberFormatter(',.2f'),
...overrides,
}) as InputColumn;

const makeParams = (value: unknown): ValueFormatterParams =>
({
value,
data: { metric: value },
}) as unknown as ValueFormatterParams;

test('valueFormatter applies the small number format to values below one', () => {
expect(valueFormatter(makeParams(0.1), makeColumn())).toBe('10.00%');
});

test('valueFormatter keeps the plain number format for values of one or more', () => {
expect(valueFormatter(makeParams(1234.56), makeColumn())).toBe('1,234.56');
});

test('valueFormatter falls back to the plain formatter when no small number format is set', () => {
const noSmallFormat = makeColumn({ config: {} });
expect(valueFormatter(makeParams(0.1), noSmallFormat)).toBe('0.10');
const emptySmallFormat = makeColumn({
config: { d3SmallNumberFormat: '' },
});
expect(valueFormatter(makeParams(0.1), emptySmallFormat)).toBe('0.10');
const nullSmallFormat = makeColumn({
config: { d3SmallNumberFormat: null },
});
expect(valueFormatter(makeParams(0.1), nullSmallFormat)).toBe('0.10');
});

test('valueFormatter applies the small number format to negative small values', () => {
expect(valueFormatter(makeParams(-0.1), makeColumn())).toBe('-10.00%');
});

test('valueFormatter matches formatColumnValue for small numbers', () => {
const column = makeColumn();
expect(formatColumnValue(column as unknown as DataColumnMeta, 0.1)[1]).toBe(
'10.00%',
);
expect(valueFormatter(makeParams(0.1), column)).toBe('10.00%');
});

test('valueFormatter applies the small number format to currency columns', () => {
const currencyColumn = makeColumn({
formatter: new CurrencyFormatter({
d3Format: '$,.2f',
currency: { symbol: 'USD', symbolPosition: 'prefix' },
}),
config: {
d3SmallNumberFormat: '.2%',
currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' },
},
});
expect(
formatColumnValue(currencyColumn as unknown as DataColumnMeta, 0.1)[1],
).toBe('$ 10.00');
expect(valueFormatter(makeParams(0.1), currencyColumn)).toBe('$ 10.00');
});
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,32 @@ export const valueFormatter = (
value !== '' &&
!(value instanceof DateWithFormatter && isEmptyDateInput(value.input))
) {
// Mirror formatColumnValue: small numbers (|value| < 1) in numeric
// columns use the column's small number format when one is set, so grid
// cells match the drill-to-detail display instead of the plain number
// format. A null/empty d3SmallNumberFormat falls back to the plain
// formatter (getSmallNumberFormatter returns it unchanged).
const isSmallNumber =
col.dataType === GenericDataType.Numeric &&
typeof value === 'number' &&
Math.abs(value) < 1;
const formatter = isSmallNumber
? getSmallNumberFormatter(
col.formatter,
col.config?.d3SmallNumberFormat,
col.config?.currencyFormat,
)
: col.formatter;
// Fall back to String(value) rather than the raw value: value can be a
// DateWithFormatter/Date (or other object) when col.formatter is unset or
// returns a falsy result, and returning that raw object here - though it
// satisfies this function's `: string` signature at compile time since
// `value`'s param type is loosely typed - crashes React with "Objects are
// not valid as a React child" once a cell renderer renders it directly.
if (col.formatter instanceof CurrencyFormatter) {
return (
col.formatter(value, data, col.currencyCodeColumn) || String(value)
);
if (formatter instanceof CurrencyFormatter) {
return formatter(value, data, col.currencyCodeColumn) || String(value);
}
return col.formatter?.(value) || String(value);
return formatter?.(value) || String(value);
}
if (node?.level === -1) {
return '';
Expand Down
27 changes: 8 additions & 19 deletions superset/charts/client_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1009,17 +1009,13 @@ def is_small_number(value: Any) -> bool:
return abs(float(value)) < 1


def configured_small_number_format(
config: dict[str, Any], applies: bool
) -> Optional[str]:
def configured_small_number_format(config: dict[str, Any]) -> Optional[str]:
"""
The small-number format a column config sets, or ``None``.

``applies`` is false for a chart that ignores the format. A cleared Select
leaves a blank string behind, which the browser treats as unset.
A cleared Select leaves a blank string behind, which the browser treats
as unset.
"""
if not applies:
return None
return (config.get("d3SmallNumberFormat") or "").strip() or None


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

def label_of(name: str) -> str:
"""Return the column label as it appears in ``df`` (verbose-renamed)."""
Expand Down Expand Up @@ -1926,9 +1919,7 @@ def label_of(name: str) -> str:
detected_currency,
row_currency_context,
fallback_to_detected=False,
small_d3_format=configured_small_number_format(
own_config, applies_small_number_format
),
small_d3_format=configured_small_number_format(own_config),
small_currency=own_config.get("currencyFormat"),
)
continue
Expand Down Expand Up @@ -1975,9 +1966,7 @@ def label_of(name: str) -> str:
# The small-number format has no dataset-level counterpart, and the
# browser pairs it with the column config's own currency rather than
# the resolved one, so both come straight from ``config``.
small_number_format = configured_small_number_format(
config, applies_small_number_format
)
small_number_format = configured_small_number_format(config)

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

Expand Down
21 changes: 12 additions & 9 deletions tests/unit_tests/charts/test_client_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4092,11 +4092,12 @@ def test_table_small_number_format_ignores_a_saved_currency() -> None:
assert formatted["amount"].tolist() == ["50.0%", "$ 12.50"]


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

assert ag_grid["amount"].tolist() == ["0.50", "12.50"]
assert ag_grid["amount"].tolist() == ["50.0%", "12.50"]
assert plain["amount"].tolist() == ["50.0%", "12.50"]


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


def test_table_derived_small_number_format_uses_its_own_currency() -> None:
Expand Down
Loading