Skip to content

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

Gdgt 912 update scalar second tab and configuration to support color (#67877)

Nick Fitzpatrick3302e9cafda8
diff --git a/.loki/reference/chrome_laptop_viz_Scalar_With_Formatting_And_Hover.png b/.loki/reference/chrome_laptop_viz_Scalar_With_Formatting_And_Hover.png
new file mode 100644
index 00000000000..4f11017321c
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Scalar_With_Formatting_And_Hover.png differ
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index bc8cc05b618..a36952f6d5e 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -313,6 +313,7 @@ export type VisualizationSettings = {
"scalar.field"?: string;
"scalar.switch_positive_negative"?: boolean;
"scalar.compact_primary_number"?: boolean;
+ "scalar.segments"?: ScalarSegment[];
// Pie Settings
"pie.dimension"?: string | string[];
@@ -492,3 +493,10 @@ export type ListViewColumns = {
right: string[];
image?: string;
};
+
+export type ScalarSegment = {
+ min: number;
+ max: number;
+ color: string;
+ label?: string;
+};
diff --git a/frontend/src/metabase-types/api/mocks/card.ts b/frontend/src/metabase-types/api/mocks/card.ts
index 88431485eaf..a3b5625a9c5 100644
--- a/frontend/src/metabase-types/api/mocks/card.ts
+++ b/frontend/src/metabase-types/api/mocks/card.ts
@@ -7,6 +7,7 @@ import type {
ModerationReview,
NativeDatasetQuery,
PublicCard,
+ ScalarSegment,
SeriesOrderSetting,
StructuredDatasetQuery,
TableColumnOrderSetting,
@@ -174,3 +175,12 @@ export const createMockPieRow = (opts?: Partial<PieRow>): PieRow => ({
originalName: "Doohickey",
...opts,
});
+
+export const createMockSegmentFormatting = (opts?: Partial<ScalarSegment>) => ({
+ label: "good",
+ min: 0,
+ max: 1,
+ // eslint-disable-next-line no-color-literals
+ color: "#7172AD",
+ ...opts,
+});
diff --git a/frontend/src/metabase/common/components/ColorPill/ColorPill.module.css b/frontend/src/metabase/common/components/ColorPill/ColorPill.module.css
index 8fe0e9e3e5a..ca7355f6c97 100644
--- a/frontend/src/metabase/common/components/ColorPill/ColorPill.module.css
+++ b/frontend/src/metabase/common/components/ColorPill/ColorPill.module.css
@@ -22,6 +22,12 @@
border-style: dashed;
}
+.XSmall {
+ width: 0.5rem;
+ height: 0.5rem;
+ padding: 0;
+}
+
.Small {
width: 1.125rem;
height: 1.125rem;
diff --git a/frontend/src/metabase/common/components/ColorPill/ColorPill.tsx b/frontend/src/metabase/common/components/ColorPill/ColorPill.tsx
index d673511f4e6..e90c2be876d 100644
--- a/frontend/src/metabase/common/components/ColorPill/ColorPill.tsx
+++ b/frontend/src/metabase/common/components/ColorPill/ColorPill.tsx
@@ -53,6 +53,7 @@ export const ColorPill = ({
ColorPillS.ColorPill,
CS.flexNoShrink,
{
+ [ColorPillS.XSmall]: pillSize === "xsmall",
[ColorPillS.Small]: pillSize === "small",
[ColorPillS.Medium]: pillSize === "medium",
[ColorPillS.Large]: pillSize === "large",
diff --git a/frontend/src/metabase/common/components/ColorPill/types.ts b/frontend/src/metabase/common/components/ColorPill/types.ts
index 4186c4a9772..08f3ba20f7a 100644
--- a/frontend/src/metabase/common/components/ColorPill/types.ts
+++ b/frontend/src/metabase/common/components/ColorPill/types.ts
@@ -1 +1 @@
-export type PillSize = "small" | "medium" | "large";
+export type PillSize = "xsmall" | "small" | "medium" | "large";
diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts
index ba4a32b0e89..307deca70a5 100644
--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts
+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts
@@ -45,6 +45,7 @@ export const useChartSettingsSections = ({
"display",
"axes",
"ranges",
+ "formatting",
// include all section names so any forgotten sections are sorted to the end
...names.map((x) => x.toLowerCase()),
];
diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/DashboardChartSettings/DashboardChartSettings.tsx b/frontend/src/metabase/visualizations/components/ChartSettings/DashboardChartSettings/DashboardChartSettings.tsx
index 61588435b1a..f77925ffeab 100644
--- a/frontend/src/metabase/visualizations/components/ChartSettings/DashboardChartSettings/DashboardChartSettings.tsx
+++ b/frontend/src/metabase/visualizations/components/ChartSettings/DashboardChartSettings/DashboardChartSettings.tsx
@@ -87,7 +87,7 @@ export const DashboardChartSettings = ({
return (
<Flex justify="unset" align="unset" wrap="nowrap" h="100%">
<BaseChartSettings
- flex="1 0 0"
+ flex="0 0 400px"
series={series}
onChange={setTempSettings}
chartSettings={chartSettings}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.styled.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.styled.tsx
index 13b31382bc1..1fc24ca86b9 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.styled.tsx
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.styled.tsx
@@ -25,6 +25,7 @@ export const ScalarValueWrapper = styled.h1<ScalarValueWrapperProps>`
font-size: ${(props) => props.fontSize};
line-height: ${(props) => props.lineHeight ?? "var(--mantine-line-height)"};
cursor: pointer;
+ color: ${({ color }) => color};
&:hover {
color: var(--mb-color-brand);
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.tsx
index 09d3b16e8a4..0526f7b9b79 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.tsx
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.tsx
@@ -24,6 +24,7 @@ interface ScalarValueProps {
gridSize?: VisualizationGridSize;
totalNumGridCols?: number;
fontFamily: string;
+ color?: string;
}
export const ScalarValue = ({
@@ -33,6 +34,7 @@ export const ScalarValue = ({
gridSize,
totalNumGridCols,
fontFamily,
+ color = "inherit",
}: ScalarValueProps) => {
const {
other: { number: numberTheme },
@@ -72,6 +74,7 @@ export const ScalarValue = ({
fontSize={fontSize}
lineHeight={numberTheme?.value?.lineHeight}
data-testid="scalar-value"
+ color={color}
>
{value ?? t`null`}
</ScalarValueWrapper>
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
index 97335e73166..fdd10a932ae 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.tsx
@@ -1,32 +1,31 @@
import { t } from "ttag";
import _ from "underscore";
-// import Button from "metabase/common/components/Button";
import { ColorSelector } from "metabase/common/components/ColorSelector";
import CS from "metabase/css/core/index.css";
import { color } from "metabase/lib/colors";
import { getAccentColors } from "metabase/lib/colors/groups";
-import { Box, Button, Icon, NumberInput, TextInput } from "metabase/ui";
+import { Box, Button, Icon, NumberInput, Text } from "metabase/ui";
+import type { ScalarSegment } from "metabase-types/api";
+
+import { ChartSettingInput } from "../ChartSettingInput";
import S from "./ChartSettingSegmentsEditor.module.css";
-export type Segment = {
- min: number;
- max: number;
- color: string;
- label?: string;
-};
+export interface ChartSettingSegmentsEditorProps {
+ value: ScalarSegment[];
+ onChange: (value: ScalarSegment[]) => void;
+ canRemoveAll?: boolean;
+}
export const ChartSettingSegmentsEditor = ({
value: segments,
onChange,
-}: {
- value: Segment[];
- onChange: (value: Segment[]) => void;
-}) => {
+ canRemoveAll = false,
+}: ChartSettingSegmentsEditorProps) => {
const onChangeProperty = (
index: number,
- property: keyof Segment,
+ property: keyof ScalarSegment,
value: number | string,
) =>
onChange([
@@ -37,78 +36,89 @@ export const ChartSettingSegmentsEditor = ({
return (
<Box px="1.5rem">
- <table className={S.Table}>
- <thead>
- <tr>
- <th />
- <th>{t`Label`}</th>
- <th>{t`Min`}</th>
- <th>{t`Max`}</th>
- </tr>
- </thead>
- <tbody>
- {segments.map((segment, index) => (
- <tr key={index}>
- <td>
- <ColorSelector
- pillSize="large"
- className={S.ColorPill}
- value={segment.color}
- colors={getColorPalette()}
- onChange={(color) => onChangeProperty(index, "color", color)}
- />
- </td>
- <td>
- <TextInput
- value={segment.label}
- placeholder={t`Optional`}
- onChange={(e) =>
- onChangeProperty(index, "label", e.target.value)
- }
- />
- </td>
- <td>
- <NumberInput
- className={CS.full}
- value={segment.min}
- onBlur={(e) => {
- const newValue = parseFloat(e.target.value);
- if (newValue !== segment.min) {
- onChangeProperty(index, "min", newValue);
- }
- }}
- placeholder={t`Min`}
- w="4rem"
- />
- </td>
- <td>
- <NumberInput
- className={CS.full}
- value={segment.max}
- onBlur={(e) => {
- const newValue = parseFloat(e.target.value);
- if (newValue !== segment.max) {
- onChangeProperty(index, "max", newValue);
- }
- }}
- placeholder={t`Max`}
- w="4rem"
- />
- </td>
- <td>
- {segments.length > 1 && (
- <Button
- leftSection={<Icon name="trash" c="text-tertiary" />}
- onClick={() =>
- onChange(segments.filter((v, i) => i !== index))
+ {segments.length > 0 ? (
+ <table className={S.Table}>
+ <thead>
+ <tr>
+ <th />
+ <th>{t`Label`}</th>
+ <th>{t`Min`}</th>
+ <th>{t`Max`}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {segments.map((segment, index) => (
+ <tr key={index}>
+ <td>
+ <ColorSelector
+ pillSize="large"
+ className={S.ColorPill}
+ value={segment.color}
+ colors={getColorPalette()}
+ onChange={(color) =>
+ onChangeProperty(index, "color", color)
}
/>
- )}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
+ </td>
+ <td>
+ <ChartSettingInput
+ value={segment.label}
+ placeholder={t`Label for this range (optional)`}
+ onChange={(val) => onChangeProperty(index, "label", val)}
+ />
+ </td>
+ <td>
+ <NumberInput
+ className={CS.full}
+ value={segment.min}
+ onBlur={(e) => {
+ const newValue = parseFloat(e.target.value);
+ if (newValue !== segment.min) {
+ onChangeProperty(index, "min", newValue);
+ }
+ }}
+ placeholder={t`Min`}
+ w="4rem"
+ />
+ </td>
+ <td>
+ <NumberInput
+ className={CS.full}
+ value={segment.max}
+ onBlur={(e) => {
+ const newValue = parseFloat(e.target.value);
+ if (newValue !== segment.max) {
+ onChangeProperty(index, "max", newValue);
+ }
+ }}
+ placeholder={t`Max`}
+ w="4rem"
+ />
+ </td>
+ <td>
+ {(segments.length > 1 || canRemoveAll) && (
+ <Button
+ leftSection={<Icon name="trash" c="text-tertiary" />}
+ onClick={() =>
+ onChange(segments.filter((v, i) => i !== index))
+ }
+ />
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ ) : (
+ <Text
+ ta="center"
+ c="text-secondary"
+ mt="2.5rem"
+ mb="3rem"
+ lh="1.25rem"
+ px="1.5rem"
+ >{t`Add color ranges to make this number change color depending on it's value`}</Text>
+ )}
<Button
leftSection={<Icon name="add" />}
onClick={() => onChange(segments.concat(newSegment(segments)))}
@@ -130,7 +140,7 @@ function getColorPalette() {
];
}
-function newSegment(segments: Segment[]) {
+function newSegment(segments: ScalarSegment[]) {
const palette = getColorPalette();
const lastSegment = segments[segments.length - 1];
const lastColorIndex = lastSegment
@@ -146,8 +156,5 @@ function newSegment(segments: Segment[]) {
max: lastSegment ? lastSegment.max * 2 : 1,
color: nextColor,
label: "",
- key: newSegmentKey(),
};
}
-
-const newSegmentKey = () => `gauge-segment-${_.uniqueId()}`;
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.unit.spec.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.unit.spec.tsx
index 06e0511f9fc..7ccdca3a0f1 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSegmentsEditor/ChartSettingSegmentsEditor.unit.spec.tsx
@@ -1,13 +1,14 @@
import userEvent from "@testing-library/user-event";
import { fireEvent, render, screen, within } from "__support__/ui";
+import type { ScalarSegment } from "metabase-types/api";
import {
ChartSettingSegmentsEditor,
- type Segment,
+ type ChartSettingSegmentsEditorProps,
} from "./ChartSettingSegmentsEditor";
-const createMockSegment = (opts?: Partial<Segment>): Segment => {
+const createMockSegment = (opts?: Partial<ScalarSegment>): ScalarSegment => {
return { label: "", min: 0, max: 100, color: "red", ...opts };
};
@@ -16,10 +17,14 @@ const DEFAULT_VALUE = [
createMockSegment({ label: "good", min: 100, max: 200, color: "green" }),
];
-const setup = () => {
+const setup = (props: Partial<ChartSettingSegmentsEditorProps> = {}) => {
const onChange = jest.fn();
render(
- <ChartSettingSegmentsEditor value={DEFAULT_VALUE} onChange={onChange} />,
+ <ChartSettingSegmentsEditor
+ value={DEFAULT_VALUE}
+ onChange={onChange}
+ {...props}
+ />,
);
return { onChange };
};
@@ -32,7 +37,7 @@ it("Should render a segment editor", () => {
const firstRow = screen.getAllByRole("row").at(1) as HTMLElement;
- expect(within(firstRow).getByPlaceholderText(/Optional/)).toHaveValue("bad");
+ expect(within(firstRow).getByPlaceholderText(/optional/)).toHaveValue("bad");
expect(within(firstRow).getByPlaceholderText(/Min/)).toHaveValue("0");
expect(within(firstRow).getByPlaceholderText(/Max/)).toHaveValue("100");
});
@@ -68,6 +73,26 @@ it("Should allow you to remove a segment", async () => {
]);
});
+it("Should not allow you to remove the last segment", async () => {
+ setup({ value: [DEFAULT_VALUE[0]] });
+
+ expect(await screen.findByDisplayValue("bad")).toBeInTheDocument();
+
+ expect(screen.queryAllByRole("img", { name: /trash/ })).toHaveLength(0);
+});
+
+it("Should allow you to remove all segments if canRemoveAll is passed", async () => {
+ const { onChange } = setup({ value: [DEFAULT_VALUE[0]], canRemoveAll: true });
+
+ expect(await screen.findAllByRole("img", { name: /trash/ })).toHaveLength(1);
+
+ await userEvent.click(
+ (await screen.findAllByRole("img", { name: /trash/ })).at(0) as HTMLElement,
+ );
+
+ expect(onChange).toHaveBeenCalledWith([]);
+});
+
it("Should allow you to add a new segment with appropriate defaults", async () => {
const { onChange } = setup();
@@ -114,3 +139,17 @@ it("Should not call onChange when blurring without changing value", async () =>
expect(onChange).not.toHaveBeenCalled();
});
+
+it("should show a placeholder if there are no segments", async () => {
+ const { onChange } = setup({ value: [], canRemoveAll: true });
+
+ expect(await screen.findByText(/Add color ranges/)).toBeInTheDocument();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: /Add a range/ }),
+ );
+
+ expect(onChange).toHaveBeenCalledWith([
+ expect.objectContaining({ min: 0, max: 1, color: expect.anything() }),
+ ]);
+});
diff --git a/frontend/src/metabase/visualizations/lib/scalar_utils.ts b/frontend/src/metabase/visualizations/lib/scalar_utils.ts
deleted file mode 100644
index 239c30150c2..00000000000
--- a/frontend/src/metabase/visualizations/lib/scalar_utils.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { formatValue } from "metabase/lib/formatting";
-import type { OptionsType } from "metabase/lib/formatting/types";
-import type { RowValue } from "metabase-types/api";
-
-export const COMPACT_MAX_WIDTH = 250;
-export const COMPACT_WIDTH_PER_DIGIT = 25;
-export const COMPACT_MIN_LENGTH = 6;
-
-function checkShouldCompact(fullValue: string, width: number) {
- const expectedCompactWidth = fullValue.length * COMPACT_WIDTH_PER_DIGIT;
- return (
- fullValue.length > COMPACT_MIN_LENGTH &&
- (width < COMPACT_MAX_WIDTH || width < expectedCompactWidth)
- );
-}
-
-export function compactifyValue(
- value: RowValue,
- width: number,
- formatOptions: OptionsType = {},
-) {
- const fullScalarValue = formatValue(value, {
- ...formatOptions,
- compact: false,
- });
- const canCompact = typeof fullScalarValue === "string";
- if (!canCompact) {
- return { displayValue: fullScalarValue, fullScalarValue };
- }
-
- const displayValue =
- formatOptions.compact || checkShouldCompact(fullScalarValue, width)
- ? formatValue(value, {
- ...formatOptions,
- compact: true,
- })
- : fullScalarValue;
-
- return { displayValue, fullScalarValue };
-}
diff --git a/frontend/src/metabase/visualizations/lib/scalar_utils.tsx b/frontend/src/metabase/visualizations/lib/scalar_utils.tsx
new file mode 100644
index 00000000000..e3e5659a654
--- /dev/null
+++ b/frontend/src/metabase/visualizations/lib/scalar_utils.tsx
@@ -0,0 +1,88 @@
+import { ColorPill } from "metabase/common/components/ColorPill";
+import { formatValue } from "metabase/lib/formatting";
+import type { OptionsType } from "metabase/lib/formatting/types";
+import { Text } from "metabase/ui";
+import { color } from "metabase/ui/utils/colors";
+import type { RowValue, ScalarSegment } from "metabase-types/api";
+
+export const COMPACT_MAX_WIDTH = 250;
+export const COMPACT_WIDTH_PER_DIGIT = 25;
+export const COMPACT_MIN_LENGTH = 6;
+
+function checkShouldCompact(fullValue: string, width: number) {
+ const expectedCompactWidth = fullValue.length * COMPACT_WIDTH_PER_DIGIT;
+ return (
+ fullValue.length > COMPACT_MIN_LENGTH &&
+ (width < COMPACT_MAX_WIDTH || width < expectedCompactWidth)
+ );
+}
+
+export function compactifyValue(
+ value: RowValue,
+ width: number,
+ formatOptions: OptionsType = {},
+) {
+ const fullScalarValue = formatValue(value, {
+ ...formatOptions,
+ compact: false,
+ });
+ const canCompact = typeof fullScalarValue === "string";
+ if (!canCompact) {
+ return { displayValue: fullScalarValue, fullScalarValue };
+ }
+
+ const displayValue =
+ formatOptions.compact || checkShouldCompact(fullScalarValue, width)
+ ? formatValue(value, {
+ ...formatOptions,
+ compact: true,
+ })
+ : fullScalarValue;
+
+ return { displayValue, fullScalarValue };
+}
+
+const DEFAULT_COLOR = color("text-primary");
+
+export function getColor(_value: RowValue, segments?: ScalarSegment[]) {
+ const value = parseInt(String(_value));
+
+ if (!segments || segments.length === 0 || Number.isNaN(value)) {
+ return DEFAULT_COLOR;
+ }
+
+ const segment = segments.find((s) => s.min <= value && value <= s.max);
+
+ if (!segment || !segment.color) {
+ return DEFAULT_COLOR;
+ }
+ return segment.color;
+}
+
+export function getTooltipContent(segments?: ScalarSegment[]) {
+ if (!segments || segments.length === 0) {
+ return null;
+ }
+
+ return (
+ <table style={{ borderSpacing: "0.75rem 0.25rem" }}>
+ <tbody>
+ {segments.map(({ color, min, max, label }: ScalarSegment, index) => (
+ <tr key={index}>
+ <td>
+ <ColorPill color={color} pillSize="xsmall" />
+ </td>
+ <td>
+ <Text c="inherit" lh="md">{`${min} - ${max}`}</Text>
+ </td>
+ <td>
+ <Text c="inherit" lh="md">
+ {label}
+ </Text>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
diff --git a/frontend/src/metabase/visualizations/lib/utils.js b/frontend/src/metabase/visualizations/lib/utils.js
index 73667051245..b60f9d4a41f 100644
--- a/frontend/src/metabase/visualizations/lib/utils.js
+++ b/frontend/src/metabase/visualizations/lib/utils.js
@@ -523,3 +523,6 @@ export function findSensibleSankeyColumns(data) {
metric: metricColumn.name,
};
}
+
+export const segmentIsValid = ({ min, max }) =>
+ !isNaN(min) && !isNaN(max) && min !== null && max !== null;
diff --git a/frontend/src/metabase/visualizations/visualizations/Gauge/Gauge.jsx b/frontend/src/metabase/visualizations/visualizations/Gauge/Gauge.jsx
index 99665065f3f..a50ec9722b6 100644
--- a/frontend/src/metabase/visualizations/visualizations/Gauge/Gauge.jsx
+++ b/frontend/src/metabase/visualizations/visualizations/Gauge/Gauge.jsx
@@ -11,6 +11,7 @@ import { formatValue } from "metabase/lib/formatting";
import { color } from "metabase/ui/utils/colors";
import { ChartSettingSegmentsEditor } from "metabase/visualizations/components/settings/ChartSettingSegmentsEditor";
import { columnSettings } from "metabase/visualizations/lib/settings/column";
+import { segmentIsValid } from "metabase/visualizations/lib/utils";
import {
getDefaultSize,
getMinSize,
@@ -57,8 +58,6 @@ const ARC_DEGREES = 180 + 45 * 2; // semicircle plus a bit
const radians = (degrees) => (degrees * Math.PI) / 180;
const degrees = (radians) => (radians * 180) / Math.PI;
-const segmentIsValid = (s) => !isNaN(s.min) && !isNaN(s.max);
-
export default class Gauge extends Component {
static getUiName = () => t`Gauge`;
static identifier = "gauge";
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx
new file mode 100644
index 00000000000..c2d39d62a9a
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx
@@ -0,0 +1,95 @@
+// @ts-expect-error There is no type definition
+import createAsyncCallback from "@loki/create-async-callback";
+import { expect, userEvent, within } from "@storybook/test";
+
+import { VisualizationWrapper } from "__support__/storybook";
+import { NumberColumn } from "__support__/visualizations";
+import { Box, SimpleGrid } from "metabase/ui";
+import { registerVisualization } from "metabase/visualizations";
+import Visualization from "metabase/visualizations/components/Visualization";
+import type { Series } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockSegmentFormatting,
+} from "metabase-types/api/mocks";
+
+import { Scalar } from "./Scalar";
+
+export default {
+ title: "viz/Scalar",
+ component: Scalar,
+};
+
+// @ts-expect-error: incompatible prop types with registerVisualization
+registerVisualization(Scalar);
+
+const MOCK_SERIES = [
+ {
+ card: createMockCard({ name: "Card", display: "scalar" }),
+ data: {
+ cols: [NumberColumn({ name: "Count" })],
+ rows: [[67]],
+ },
+ },
+] as Series;
+
+const SETTINGS = {
+ "scalar.segments": [
+ createMockSegmentFormatting({
+ label: "bad",
+ min: 0,
+ max: 50,
+ color: "#F00",
+ }),
+ createMockSegmentFormatting({
+ label: "good",
+ min: 50,
+ max: 100,
+ color: "#0F0",
+ }),
+ ],
+};
+
+export const WithFormattingAndHover = () => {
+ return (
+ <VisualizationWrapper>
+ <SimpleGrid cols={2} w={500}>
+ <Box h={250}>
+ <Visualization rawSeries={MOCK_SERIES} width={500} />
+ </Box>
+ <Box h={250}>
+ <Visualization
+ rawSeries={MOCK_SERIES}
+ width={250}
+ settings={SETTINGS}
+ />
+ </Box>
+ <Box h={250}>
+ <Visualization
+ rawSeries={MOCK_SERIES}
+ width={250}
+ settings={SETTINGS}
+ />
+ </Box>
+ </SimpleGrid>
+ </VisualizationWrapper>
+ );
+};
+
+WithFormattingAndHover.play = async ({
+ canvasElement,
+}: {
+ canvasElement: HTMLCanvasElement;
+}) => {
+ const asyncCallback = createAsyncCallback();
+ const canvas = within(canvasElement.parentElement as HTMLElement);
+ const value = (await canvas.findAllByTestId("scalar-value"))[2];
+
+ await userEvent.hover(value);
+ value.classList.add("pseudo-hover");
+
+ await expect(await canvas.findByRole("tooltip")).toBeInTheDocument();
+ expect(value.classList.contains("pseudo-hover")).toBe(true);
+
+ asyncCallback();
+};
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
index 1d5f049dc74..92ee8d8ca2e 100644
--- a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
@@ -3,14 +3,21 @@ import { t } from "ttag";
import _ from "underscore";
import DashboardS from "metabase/css/dashboard.module.css";
+import { Box, Tooltip } from "metabase/ui";
import {
ScalarValue,
ScalarWrapper,
} from "metabase/visualizations/components/ScalarValue/ScalarValue";
import { TransformedVisualization } from "metabase/visualizations/components/TransformedVisualization";
-import { compactifyValue } from "metabase/visualizations/lib/scalar_utils";
+import { ChartSettingSegmentsEditor } from "metabase/visualizations/components/settings/ChartSettingSegmentsEditor";
+import {
+ compactifyValue,
+ getColor,
+ getTooltipContent,
+} from "metabase/visualizations/lib/scalar_utils";
import { columnSettings } from "metabase/visualizations/lib/settings/column";
import { fieldSetting } from "metabase/visualizations/lib/settings/utils";
+import { segmentIsValid } from "metabase/visualizations/lib/utils";
import {
getDefaultSize,
getMinSize,
@@ -77,6 +84,20 @@ export class Scalar extends Component<
},
]) => cols.length < 2,
}),
+ "scalar.segments": {
+ get section() {
+ return t`Conditional colors`;
+ },
+ getDefault() {
+ return [];
+ },
+ widget: ChartSettingSegmentsEditor,
+ persistDefault: true,
+ noPadding: true,
+ props: {
+ canRemoveAll: true,
+ },
+ },
...columnSettings({
getColumns: (
[
@@ -174,6 +195,11 @@ export class Scalar extends Component<
jsx: true,
};
+ const segments = settings["scalar.segments"]?.filter(segmentIsValid);
+
+ const color = getColor(value, segments);
+ const tooltipContent = getTooltipContent(segments);
+
const { displayValue, fullScalarValue } = compactifyValue(
value,
width,
@@ -212,16 +238,28 @@ export class Scalar extends Component<
alwaysShowTooltip={fullScalarValue !== displayValue}
isClickable={isClickable}
>
- <span onClick={handleClick} ref={(scalar) => (this._scalar = scalar)}>
- <ScalarValue
- fontFamily={fontFamily}
- gridSize={gridSize}
- height={Math.max(height - PADDING * 2, 0)}
- totalNumGridCols={totalNumGridCols}
- value={displayValue as string}
- width={Math.max(width - PADDING, 0)}
- />
- </span>
+ <Tooltip
+ label={tooltipContent}
+ position="bottom"
+ px="0.375rem"
+ py="xs"
+ disabled={!tooltipContent}
+ >
+ <Box
+ onClick={handleClick}
+ ref={(scalar) => (this._scalar = scalar)}
+ >
+ <ScalarValue
+ color={color}
+ fontFamily={fontFamily}
+ gridSize={gridSize}
+ height={Math.max(height - PADDING * 2, 0)}
+ totalNumGridCols={totalNumGridCols}
+ value={displayValue as string}
+ width={Math.max(width - PADDING, 0)}
+ />
+ </Box>
+ </Tooltip>
</ScalarValueContainer>
</ScalarWrapper>
);
diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.clj
index 664be3bea7f..02607091acf 100644
--- a/src/metabase/channel/render/body.clj
+++ b/src/metabase/channel/render/body.clj
@@ -85,6 +85,15 @@
:else
(str value)))
+(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]
+ (some (fn [{:keys [min max color]}]
+ (when (and (some? min) (some? max) (<= min value max))
+ color))
+ segments)))
+
;;; --------------------------------------------------- Rendering ----------------------------------------------------
(defn- create-remapping-lookup
@@ -374,12 +383,13 @@
[0 (first cols)])
row (first rows)
raw-value (get row row-idx)
- value (format-scalar-value timezone-id raw-value col viz-settings)]
+ value (format-scalar-value timezone-id raw-value col viz-settings)
+ color (get-color-from-segment viz-settings raw-value)]
{:attachments
nil
:content
- [:div {:style (style/style (style/scalar-style))}
+ [:div {:style (style/style (style/scalar-style color))}
(h value)]
:render/text (str value)}))
diff --git a/src/metabase/channel/render/style.clj b/src/metabase/channel/render/style.clj
index 071e722ae7f..a7ff4b70544 100644
--- a/src/metabase/channel/render/style.clj
+++ b/src/metabase/channel/render/style.clj
@@ -94,12 +94,13 @@
(defn scalar-style
"Style for a scalar display-type 'chart' in a Pulse."
- []
- (merge
- (font-style)
- {:font-size :24px
- :font-weight 700
- :color color-text-dark}))
+ ([] (scalar-style nil))
+ ([color]
+ (merge
+ (font-style)
+ {:font-size :24px
+ :font-weight 700
+ :color (or color color-text-dark)})))
(defn- register-font! [filename]
(with-open [is (io/input-stream (io/resource filename))]