Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat: allow empty min and max for scalar conditional colors (#69177)

Maksym Yakubych19d9dcb047d5
diff --git a/e2e/test/scenarios/visualizations-charts/scalar.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/scalar.cy.spec.ts
new file mode 100644
index 00000000000..a9283168f74
--- /dev/null
+++ b/e2e/test/scenarios/visualizations-charts/scalar.cy.spec.ts
@@ -0,0 +1,58 @@
+const { H } = cy;
+import Color from "color";
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+describe("scenarios > visualizations > scalar", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("should allow open-ended conditional color ranges", () => {
+ H.createQuestion({
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ display: "scalar",
+ }).then(({ body: { id } }) => {
+ cy.visit(`/question/${id}`);
+ cy.findByTestId("query-visualization-root", { timeout: 20000 })
+ .findByTestId("scalar-value")
+ .should("be.visible");
+ });
+
+ H.openVizSettingsSidebar();
+ H.sidebar().findByText("Conditional colors").click();
+
+ cy.findByRole("button", { name: /add a range/i }).click();
+
+ cy.findAllByPlaceholderText("Min").eq(0).clear().blur();
+ cy.findAllByPlaceholderText("Max").eq(0).clear().type("1000").blur();
+
+ cy.findByRole("button", { name: /add a range/i }).click();
+
+ cy.findAllByPlaceholderText("Min").eq(1).clear().type("1000").blur();
+ cy.findAllByPlaceholderText("Max").eq(1).clear().blur();
+
+ cy.findAllByTestId("color-selector-button").eq(1).click();
+ H.popover()
+ .findAllByRole("button")
+ .eq(4)
+ .then(($button) => {
+ const color = $button.attr("aria-label");
+ cy.wrap($button).click();
+ cy.findByTestId("scalar-value").should(
+ "have.css",
+ "color",
+ Color(color).rgb().string(),
+ );
+ });
+
+ cy.findByTestId("scalar-value").realHover();
+ H.tooltip().should("contain.text", "≤ 1000").and("contain.text", "≥ 1000");
+ });
+});
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 9b6940d6d5d..4bc7e96b814 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -498,8 +498,8 @@ export type ListViewColumns = {
};
export type ScalarSegment = {
- min: number;
- max: number;
+ min: number | null;
+ max: number | null;
color: string;
label?: string;
};
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
index b22b365393b..bb70dde99cd 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
@@ -27,7 +27,7 @@ export const ChartSettingSegmentsEditor = ({
const onChangeProperty = (
index: number,
property: keyof ScalarSegment,
- value: number | string,
+ value: number | string | null,
) =>
onChange([
...segments.slice(0, index),
@@ -71,9 +71,11 @@ export const ChartSettingSegmentsEditor = ({
<td>
<NumberInput
className={CS.full}
- value={segment.min}
+ value={segment.min ?? ""}
onBlur={(e) => {
- const newValue = parseFloat(e.target.value);
+ const rawValue = e.target.value;
+ const newValue =
+ rawValue === "" ? null : parseFloat(rawValue);
if (newValue !== segment.min) {
onChangeProperty(index, "min", newValue);
}
@@ -85,9 +87,11 @@ export const ChartSettingSegmentsEditor = ({
<td>
<NumberInput
className={CS.full}
- value={segment.max}
+ value={segment.max ?? ""}
onBlur={(e) => {
- const newValue = parseFloat(e.target.value);
+ const rawValue = e.target.value;
+ const newValue =
+ rawValue === "" ? null : parseFloat(rawValue);
if (newValue !== segment.max) {
onChangeProperty(index, "max", newValue);
}
@@ -144,6 +148,10 @@ function getColorPalette() {
function newSegment(segments: ScalarSegment[]) {
const palette = getColorPalette();
const lastSegment = segments[segments.length - 1];
+ const lastMax =
+ typeof lastSegment?.max === "number" && Number.isFinite(lastSegment.max)
+ ? lastSegment.max
+ : null;
const lastColorIndex = lastSegment
? _.findIndex(palette, (color) => color === lastSegment.color)
: -1;
@@ -153,8 +161,8 @@ function newSegment(segments: ScalarSegment[]) {
: palette[0];
return {
- min: lastSegment ? lastSegment.max : 0,
- max: lastSegment ? lastSegment.max * 2 : 1,
+ min: lastMax !== null ? lastMax : 0,
+ max: lastMax !== null ? lastMax * 2 : 1,
color: nextColor,
label: "",
};
diff --git a/frontend/src/metabase/visualizations/lib/scalar_utils.tsx b/frontend/src/metabase/visualizations/lib/scalar_utils.tsx
index e3e5659a654..d18de975209 100644
--- a/frontend/src/metabase/visualizations/lib/scalar_utils.tsx
+++ b/frontend/src/metabase/visualizations/lib/scalar_utils.tsx
@@ -44,14 +44,44 @@ export function compactifyValue(
const DEFAULT_COLOR = color("text-primary");
+const isFiniteNumber = (value: unknown): value is number =>
+ typeof value === "number" && Number.isFinite(value);
+
+const getSegmentBounds = ({ min, max }: ScalarSegment) => ({
+ min: isFiniteNumber(min) ? min : -Infinity,
+ max: isFiniteNumber(max) ? max : Infinity,
+});
+
+const formatSegmentRange = ({ min, max }: ScalarSegment) => {
+ const hasMin = isFiniteNumber(min);
+ const hasMax = isFiniteNumber(max);
+
+ if (hasMin && hasMax) {
+ return `${min} - ${max}`;
+ }
+
+ if (hasMin) {
+ return `≥ ${min}`;
+ }
+
+ if (hasMax) {
+ return `≤ ${max}`;
+ }
+
+ return "";
+};
+
export function getColor(_value: RowValue, segments?: ScalarSegment[]) {
- const value = parseInt(String(_value));
+ const value = parseFloat(String(_value));
if (!segments || segments.length === 0 || Number.isNaN(value)) {
return DEFAULT_COLOR;
}
- const segment = segments.find((s) => s.min <= value && value <= s.max);
+ const segment = segments.find((s) => {
+ const { min, max } = getSegmentBounds(s);
+ return min <= value && value <= max;
+ });
if (!segment || !segment.color) {
return DEFAULT_COLOR;
@@ -73,7 +103,9 @@ export function getTooltipContent(segments?: ScalarSegment[]) {
<ColorPill color={color} pillSize="xsmall" />
</td>
<td>
- <Text c="inherit" lh="md">{`${min} - ${max}`}</Text>
+ <Text c="inherit" lh="md">
+ {formatSegmentRange({ min, max, color, label })}
+ </Text>
</td>
<td>
<Text c="inherit" lh="md">
diff --git a/frontend/src/metabase/visualizations/lib/utils.js b/frontend/src/metabase/visualizations/lib/utils.js
index 40ff2b4b7ba..df514194d68 100644
--- a/frontend/src/metabase/visualizations/lib/utils.js
+++ b/frontend/src/metabase/visualizations/lib/utils.js
@@ -518,5 +518,11 @@ export function findSensibleSankeyColumns(data) {
};
}
-export const segmentIsValid = ({ min, max }) =>
- !isNaN(min) && !isNaN(max) && min !== null && max !== null;
+export const segmentIsValid = (
+ { min, max },
+ { allowOpenEnded = false } = {},
+) => {
+ const hasMin = typeof min === "number" && Number.isFinite(min);
+ const hasMax = typeof max === "number" && Number.isFinite(max);
+ return allowOpenEnded ? hasMin || hasMax : hasMin && hasMax;
+};
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
index 8abc1f7639b..b257ea27b4a 100644
--- a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
@@ -198,7 +198,9 @@ export class Scalar extends Component<
jsx: true,
};
- const segments = settings["scalar.segments"]?.filter(segmentIsValid);
+ const segments = settings["scalar.segments"]?.filter((segment) =>
+ segmentIsValid(segment, { allowOpenEnded: true }),
+ );
const color = getColor(value, segments);
const tooltipContent = getTooltipContent(segments);
diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.clj
index 02607091acf..4dbfa4c5df0 100644
--- a/src/metabase/channel/render/body.clj
+++ b/src/metabase/channel/render/body.clj
@@ -88,9 +88,11 @@
(defn get-color-from-segment
"Returns the color of the first segment who's max is higher than value and min is lower than value"
[viz-settings value]
- (let [{segments :scalar.segments} viz-settings]
+ (let [{segments :scalar.segments} viz-settings
+ ->min (fn [min] (if (number? min) min Double/NEGATIVE_INFINITY))
+ ->max (fn [max] (if (number? max) max Double/POSITIVE_INFINITY))]
(some (fn [{:keys [min max color]}]
- (when (and (some? min) (some? max) (<= min value max))
+ (when (<= (->min min) value (->max max))
color))
segments)))