The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
support value and goal column selection in progress visualization (#62963)
Aleksandr Lesnenko5b450f29aa5a
diff --git a/e2e/support/helpers/e2e-viz-settings-helpers.js b/e2e/support/helpers/e2e-viz-settings-helpers.jsindex 7cf91ff81b7..a43b3f0587f 100644--- a/e2e/support/helpers/e2e-viz-settings-helpers.js+++ b/e2e/support/helpers/e2e-viz-settings-helpers.js@@ -27,3 +27,7 @@ export function openVizTypeSidebar() {export function openVizSettingsSidebar() {cy.findByTestId("viz-settings-button").click();}++export function vizSettingsSidebar() {+ return cy.findByTestId("chartsettings-sidebar");+}diff --git a/e2e/test/scenarios/visualizations-charts/progress-bar.cy.spec.js b/e2e/test/scenarios/visualizations-charts/progress-bar.cy.spec.jsindex 7aa441217d6..ed33b5d6b2b 100644--- a/e2e/test/scenarios/visualizations-charts/progress-bar.cy.spec.js+++ b/e2e/test/scenarios/visualizations-charts/progress-bar.cy.spec.js@@ -1,7 +1,7 @@const { H } = cy;import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-const { ORDERS_ID } = SAMPLE_DATABASE;+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;describe("scenarios > visualizations > progress chart", () => {beforeEach(() => {@@ -55,4 +55,221 @@ describe("scenarios > visualizations > progress chart", () => {cy.findByText("Goal exceeded").should("be.visible");});});++ it("should allow value field selection with multiple numeric columns", () => {+ const questionDetails = {+ name: "Multi-column Progress Test",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"], ["sum", ["field", ORDERS.TOTAL, null]]],+ },+ display: "progress",+ };++ H.createQuestion(questionDetails, { visitQuestion: true });++ // Open visualization settings+ H.openVizSettingsSidebar();+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Display").click();++ // Should show Value field selector since we have multiple numeric columns+ cy.findByText("Value").should("be.visible");++ // Default should be first column (Count)+ cy.findByDisplayValue("Count").should("be.visible");++ // Change to Sum of Total+ cy.findByDisplayValue("Count").click();+ });++ H.popover().within(() => {+ cy.findByText("Sum of Total").click();+ });++ // Verify the field changed+ H.vizSettingsSidebar().within(() => {+ cy.findByDisplayValue("Sum of Total").should("be.visible");+ });+ });++ it("should not show value field selector with single numeric column", () => {+ const questionDetails = {+ name: "Single Column Progress Test",+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },+ display: "progress",+ };++ H.createQuestion(questionDetails, { visitQuestion: true });++ H.openVizSettingsSidebar();+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Display").click();++ // Should NOT show Value field selector since we only have one numeric column+ cy.findByText("Value").should("not.exist");++ // Goal setting should still be visible with no dropdown since no other columns+ cy.findByText("Goal").should("be.visible");++ // No dropdown icon should be visible since there are no other columns for goal+ cy.findByPlaceholderText("Enter goal value")+ .parent()+ .parent()+ .within(() => {+ cy.icon("chevrondown").should("not.exist");+ });+ });+ });++ it("should exclude value column from goal column options and include Custom value option", () => {+ const questionDetails = {+ name: "Exclusion Test Progress",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [+ ["count"],+ ["sum", ["field", ORDERS.TOTAL, null]],+ ["avg", ["field", ORDERS.QUANTITY, null]],+ ],+ },+ display: "progress",+ };++ H.createQuestion(questionDetails, { visitQuestion: true });++ H.openVizSettingsSidebar();+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Display").click();++ // Set value field to Sum of Total+ cy.findByDisplayValue("Count").click();+ });++ H.popover().within(() => {+ cy.findByText("Sum of Total").click();+ });++ H.vizSettingsSidebar().within(() => {+ cy.findByText("Goal").parent().parent().icon("chevrondown").click();+ });++ // Should show Custom value, Count and Average of Quantity, but not Sum of Total+ H.popover().within(() => {+ cy.findByText("Custom value").should("be.visible");+ cy.findByText("Count").should("exist");+ cy.findByText("Average of Quantity").should("be.visible");+ cy.findByText("Sum of Total").should("not.exist");++ // Select Count+ cy.findByText("Count").click();+ });++ // Goal should show Count selected in the input+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Count").should("exist");+ });+ });++ it("should be backwards compatibile", () => {+ // A question with numeric `progress.goal` and no `progress.value` should render a progress bar with the goal value+ const questionDetails = {+ name: "Backwards Compat Test",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ },+ display: "progress",+ visualization_settings: {+ "progress.goal": 1000,+ },+ };++ H.createQuestion(questionDetails, { visitQuestion: true });++ H.queryBuilderMain().within(() => {+ cy.findByText("18,760").should("be.visible");+ cy.contains("Goal 1,000").should("be.visible");+ });+ });++ it("should allow switching between custom value and column reference via dropdown", () => {+ const questionDetails = {+ name: "Custom Value Toggle Test",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"], ["sum", ["field", ORDERS.TOTAL, null]]],+ },+ display: "progress",+ };++ H.createQuestion(questionDetails, { visitQuestion: true });++ H.openVizSettingsSidebar();+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Display").click();++ // Initially should show number input with placeholder+ cy.findByPlaceholderText("Enter goal value").should("be.visible");++ // Click dropdown to select a column+ cy.findByText("Goal").parent().parent().icon("chevrondown").click();+ });++ // Select Sum of Total column+ H.popover().findByText("Sum of Total").click();++ // Should now show the column name in a read-only text input+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Sum of Total").should("exist");++ // Click dropdown again to switch back to custom value+ cy.findByText("Goal").parent().parent().icon("chevrondown").click();+ });++ H.popover().within(() => {+ cy.findByText("Custom value").click();+ });++ // Should be back to number input and it should be focused+ H.vizSettingsSidebar().within(() => {+ cy.findByPlaceholderText("Enter goal value")+ .should("exist")+ .should("have.focus");+ });+ });++ it("should handle native query with both value and goal columns", () => {+ const query = 'select 75000 as "value", 100000 as "goal";';++ H.visitQuestionAdhoc({+ display: "progress",+ dataset_query: {+ type: "native",+ native: {+ query,+ },+ database: SAMPLE_DATABASE.id,+ },+ });++ // Open visualization settings to configure value and goal columns+ H.openVizSettingsSidebar();+ H.vizSettingsSidebar().within(() => {+ cy.findByText("Display").click();++ // Configure goal to use the "goal" column+ cy.findByText("Goal").parent().parent().icon("chevrondown").click();+ });++ H.popover().findByText("goal").click();++ // Verify the progress bar displays correctly with native query data+ H.queryBuilderMain().within(() => {+ // Should show the first row's value+ cy.findByText("75,000").should("be.visible");+ // Should show goal from the goal column+ cy.findByText("Goal 100,000").should("be.visible");+ });+ });});diff --git a/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.stories.tsx b/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.stories.tsxindex d2631e3ad1e..5842f270f99 100644--- a/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.stories.tsx+++ b/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.stories.tsx@@ -1,15 +1,17 @@import type { StoryFn } from "@storybook/react";-import ProgressBar, { type ProgressBarProps } from "./ProgressBar";+import { StaticVisualization } from "../StaticVisualization";+import type { StaticChartProps } from "../StaticVisualization/types";+import { BELOW_GOAL, EXCEEDS_GOAL, REACHED_GOAL, ZERO } from "./stories-data";export default {title: "Viz/Static Viz/ProgressBar",- component: ProgressBar,+ component: StaticVisualization,};-const Template: StoryFn<ProgressBarProps> = (args) => {- return <ProgressBar {...args} />;+const Template: StoryFn<StaticChartProps> = (args) => {+ return <StaticVisualization {...args} />;};export const Default = {diff --git a/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.tsx b/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.tsxindex 002d940d3ca..0ab9c1a0c5f 100644--- a/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.tsx+++ b/frontend/src/metabase/static-viz/components/ProgressBar/ProgressBar.tsx@@ -1,18 +1,27 @@import { ClipPath } from "@visx/clip-path";import { Group } from "@visx/group";import { scaleLinear } from "@visx/scale";-import { t } from "ttag";+import { useMemo } from "react";+import { c } from "ttag";++import { formatValue } from "metabase/lib/formatting";+import {+ calculateProgressMetrics,+ extractProgressValue,+ findProgressColumn,+ getGoalValue,+ getProgressColors,+ getProgressMessage,+} from "metabase/visualizations/visualizations/Progress/utils";+import type { DatasetColumn } from "metabase-types/api";-import type { ColorGetter } from "metabase/visualizations/types";--import { formatNumber } from "../../lib/numbers";import Watermark from "../../watermark.svg?component";+import type { StaticChartProps } from "../StaticVisualization/types";import { Text } from "../Text";import { CheckMarkIcon } from "./CheckMarkIcon";import { Pointer } from "./Pointer";-import type { ProgressBarData } from "./types";-import { calculatePointerLabelShift, getBarText, getColors } from "./utils";+import { calculatePointerLabelShift } from "./utils";const layout = {width: 440,@@ -33,23 +42,43 @@ const layout = {fontSize: 13,};-export interface ProgressBarProps {- data: ProgressBarData;- settings: {- color: string;- format: any;- };- getColor: ColorGetter;- hasDevWatermark?: boolean;-}--const ProgressBar = ({- data,- settings: { color, format },- getColor,+export const ProgressBar = ({+ rawSeries,+ settings,+ renderingContext,hasDevWatermark = false,-}: ProgressBarProps) => {- const colors = getColors(data, color || getColor("accent1"));+}: StaticChartProps) => {+ const {+ data: { cols, rows },+ } = rawSeries[0];++ const { data, metrics, colors, column } = useMemo(() => {+ const valueField = settings["progress.value"];+ const goalSetting = settings["progress.goal"] ?? 0;++ const column = findProgressColumn(cols, valueField);+ const columnIndex = column+ ? cols.findIndex((col: DatasetColumn) => col.name === column.name)+ : -1;++ const value = extractProgressValue(rows, columnIndex);+ const goal = getGoalValue(goalSetting, cols, rows);++ const metrics = calculateProgressMetrics(value, goal);++ const mainColor =+ settings["progress.color"] || renderingContext.getColor("accent1");+ const colors = getProgressColors(mainColor, value, goal);++ return {+ data: { value, goal },+ metrics,+ colors,+ column: column || cols[0],+ };+ }, [cols, rows, settings, renderingContext]);++ const columnSettings = settings.column?.(column) ?? {};const barWidth = layout.width - layout.margin.left - layout.margin.right;const xMin = layout.margin.left;@@ -58,18 +87,18 @@ const ProgressBar = ({const labelsY = layout.margin.top + layout.barHeight + layout.labelsMargin;const xScale = scaleLinear({- domain: [0, Math.max(data.goal, data.value)],+ domain: [0, 1],range: [0, barWidth],});- const currentX = xScale(Math.max(0, Math.min(data.goal, data.value)));-+ const currentX = xScale(metrics.barPercent);const pointerY = layout.margin.top - layout.pointer.height * 1.5;- const pointerX = xMin + Math.max(xScale(data.value), 0);+ const pointerX = xMin + xScale(metrics.arrowPercent);- const barText = getBarText(data);-- const valueText = formatNumber(data.value, format);+ const barMessage = getProgressMessage(metrics);+ const valueText = metrics.hasValidValue+ ? String(formatValue(data.value, columnSettings) ?? "—")+ : "—";const valueTextShift = calculatePointerLabelShift(valueText,@@ -97,35 +126,38 @@ const ProgressBar = ({<rectwidth={barWidth}height={layout.barHeight}- fill={colors.backgroundBar}+ fill={colors.background}/><rectwidth={currentX}height={layout.barHeight}- fill={colors.foregroundBar}+ fill={colors.foreground}/>- {barText && (- <>- <CheckMarkIcon- size={layout.iconSize}- // eslint-disable-next-line no-color-literals- color="#ffffff"- x={10}- y={(layout.barHeight - layout.iconSize) / 2}- />- <Text- fontSize={layout.fontSize}- textAnchor="start"- x={layout.iconSize + 16}- y={layout.barHeight / 2}- verticalAnchor="middle"- // eslint-disable-next-line no-color-literals- fill="#ffffff"- >- {barText}- </Text>- </>- )}+ {barMessage &&+ metrics.hasValidValue &&+ metrics.hasValidGoal &&+ (metrics.value >= metrics.goal ? (+ <>+ <CheckMarkIcon+ size={layout.iconSize}+ // eslint-disable-next-line no-color-literals+ color="#ffffff"+ x={10}+ y={(layout.barHeight - layout.iconSize) / 2}+ />+ <Text+ fontSize={layout.fontSize}+ textAnchor="start"+ x={layout.iconSize + 16}+ y={layout.barHeight / 2}+ verticalAnchor="middle"+ // eslint-disable-next-line no-color-literals+ fill="#ffffff"+ >+ {barMessage}+ </Text>+ </>+ ) : null)}</Group><Group left={pointerX} top={pointerY}><Text@@ -149,10 +181,13 @@ const ProgressBar = ({alignmentBaseline="baseline"x={layout.margin.left}>- {formatNumber(0, format)}+ {String(formatValue(0, columnSettings) ?? "0")}</Text><Text fontSize={layout.fontSize} textAnchor="end" x={xMax}>- {t`Goal ${formatNumber(data.goal, format)}`}+ {metrics.hasValidGoal+ ? c("Label showing goal value in progress chart")+ .t`Goal ${String(formatValue(data.goal, columnSettings) ?? data.goal)}`+ : c("Label when no goal is set in progress chart").t`Goal: Not set`}</Text></Group>{hasDevWatermark && (@@ -167,6 +202,3 @@ const ProgressBar = ({</svg>);};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default ProgressBar;diff --git a/frontend/src/metabase/static-viz/components/ProgressBar/index.ts b/frontend/src/metabase/static-viz/components/ProgressBar/index.tsindex 987febf37e7..0c301e437b4 100644--- a/frontend/src/metabase/static-viz/components/ProgressBar/index.ts+++ b/frontend/src/metabase/static-viz/components/ProgressBar/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./ProgressBar";+export { ProgressBar } from "./ProgressBar";diff --git a/frontend/src/metabase/static-viz/components/ProgressBar/stories-data.ts b/frontend/src/metabase/static-viz/components/ProgressBar/stories-data.tsindex a8c9ae59c90..40e0bac097f 100644--- a/frontend/src/metabase/static-viz/components/ProgressBar/stories-data.ts+++ b/frontend/src/metabase/static-viz/components/ProgressBar/stories-data.ts@@ -1,63 +1,143 @@export const ZERO = {- data: {- value: 0,- goal: 100000,- },- settings: {- format: {- number_style: "currency",- currency: "USD",- currency_style: "symbol",- decimals: 0,+ rawSeries: [+ {+ data: {+ cols: [+ {+ name: "value",+ display_name: "Value",+ base_type: "type/Number",+ semantic_type: "type/Number",+ },+ ],+ rows: [[0]],+ },+ card: {+ display: "progress",+ visualization_settings: {+ "progress.goal": 100000,+ "progress.color": "#84BB4C",+ column_settings: {+ '["name","value"]': {+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+ decimals: 0,+ },+ },+ },+ },},- color: "#84BB4C",+ ],+ renderingContext: {+ getColor: (color: string) => (color === "accent1" ? "#509EE3" : color),},};export const BELOW_GOAL = {- data: {- value: 30000,- goal: 100000,- },- settings: {- format: {- number_style: "currency",- currency: "USD",- currency_style: "symbol",- decimals: 0,+ rawSeries: [+ {+ data: {+ cols: [+ {+ name: "value",+ display_name: "Value",+ base_type: "type/Number",+ semantic_type: "type/Number",+ },+ ],+ rows: [[30000]],+ },+ card: {+ display: "progress",+ visualization_settings: {+ "progress.goal": 100000,+ "progress.color": "#84BB4C",+ column_settings: {+ '["name","value"]': {+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+ decimals: 0,+ },+ },+ },+ },},- color: "#84BB4C",+ ],+ renderingContext: {+ getColor: (color: string) => (color === "accent1" ? "#509EE3" : color),},};export const REACHED_GOAL = {- data: {- value: 100000,- goal: 100000,- },- settings: {- format: {- number_style: "currency",- currency: "USD",- currency_style: "symbol",- decimals: 0,+ rawSeries: [+ {+ data: {+ cols: [+ {+ name: "value",+ display_name: "Value",+ base_type: "type/Number",+ semantic_type: "type/Number",+ },+ ],+ rows: [[100000]],+ },+ card: {+ display: "progress",+ visualization_settings: {+ "progress.goal": 100000,+ "progress.color": "#84BB4C",+ column_settings: {+ '["name","value"]': {+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+ decimals: 0,+ },+ },+ },+ },},- color: "#84BB4C",+ ],+ renderingContext: {+ getColor: (color: string) => (color === "accent1" ? "#509EE3" : color),},};export const EXCEEDS_GOAL = {- data: {- value: 135000,- goal: 100000,- },- settings: {- format: {- number_style: "currency",- currency: "USD",- currency_style: "symbol",- decimals: 0,+ rawSeries: [+ {+ data: {+ cols: [+ {+ name: "value",+ display_name: "Value",+ base_type: "type/Number",+ semantic_type: "type/Number",+ },+ ],+ rows: [[135000]],+ },+ card: {+ display: "progress",+ visualization_settings: {+ "progress.goal": 100000,+ "progress.color": "#84BB4C",+ column_settings: {+ '["name","value"]': {+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+ decimals: 0,+ },+ },+ },+ },},- color: "#84BB4C",+ ],+ renderingContext: {+ getColor: (color: string) => (color === "accent1" ? "#509EE3" : color),},};diff --git a/frontend/src/metabase/static-viz/components/ProgressBar/utils.ts b/frontend/src/metabase/static-viz/components/ProgressBar/utils.tsindex a9f5f914975..fa9bc6cbc8b 100644--- a/frontend/src/metabase/static-viz/components/ProgressBar/utils.ts+++ b/frontend/src/metabase/static-viz/components/ProgressBar/utils.ts@@ -1,41 +1,5 @@-import Color from "color";-import { t } from "ttag";-import { measureTextWidth } from "metabase/static-viz/lib/text";-import type { ProgressBarData } from "./types";--const createPalette = (color: string) => ({- light: Color(color).lighten(0.25).hex(),- main: color,- dark: Color(color).darken(0.3).hex(),-});--export const getColors = ({ value, goal }: ProgressBarData, color: string) => {- const palette = createPalette(color);- const isExceeded = value > goal;-- const backgroundBar = isExceeded ? palette.dark : palette.light;- const foregroundBar = palette.main;- const pointer = isExceeded ? palette.dark : palette.main;-- return {- backgroundBar,- foregroundBar,- pointer,- };-};--export const getBarText = ({ value, goal }: ProgressBarData) => {- if (value === goal) {- return t`Goal met`;- } else if (value > goal) {- return t`Goal exceeded`;- }-- return null;-};-export const calculatePointerLabelShift = (valueText: string,pointerX: number,diff --git a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsxindex 5ad5758ce5f..6bb15017296 100644--- a/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx+++ b/frontend/src/metabase/static-viz/components/StaticVisualization/StaticVisualization.tsx@@ -6,6 +6,7 @@ import type { StaticVisualizationProps } from "metabase/visualizations/types";import { ComboChart } from "../ComboChart";import { FunnelBarChart } from "../FunnelBarChart";import { PieChart } from "../PieChart/PieChart";+import { ProgressBar } from "../ProgressBar";import { StaticRowChart } from "../RowChart/RowChart";import { SankeyChart } from "../SankeyChart";import { ScalarChart } from "../ScalarChart";@@ -52,6 +53,8 @@ export const StaticVisualization = ({return <PieChart {...props} />;case "sankey":return <SankeyChart {...props} />;+ case "progress":+ return <ProgressBar {...props} />;case "row":// TODO: replace with an ECharts implementationreturn <StaticRowChart {...props} />;diff --git a/frontend/src/metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart.tsx b/frontend/src/metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart.tsxindex 1f10d55dd13..a8bbda06b7d 100644--- a/frontend/src/metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart.tsx+++ b/frontend/src/metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart.tsx@@ -1,14 +1,9 @@import type { ColorPalette } from "metabase/lib/colors/types";import Funnel from "metabase/static-viz/components/FunnelChart";import Gauge from "metabase/static-viz/components/Gauge";-import ProgressBar from "metabase/static-viz/components/ProgressBar";import { createColorGetter } from "metabase/static-viz/lib/colors";-export type LegacyStaticChartType =- | "progress"- | "waterfall"- | "gauge"- | "funnel";+export type LegacyStaticChartType = "gauge" | "funnel";export interface LegacyStaticChartProps {type: LegacyStaticChartType;@@ -31,8 +26,6 @@ export const LegacyStaticChart = ({switch (type) {case "gauge":return <Gauge {...chartProps} />;- case "progress":- return <ProgressBar {...chartProps} />;case "funnel":return <Funnel {...chartProps} />;}diff --git a/frontend/src/metabase/static-viz/register.js b/frontend/src/metabase/static-viz/register.jsindex aafbae9d9d6..282bc078a74 100644--- a/frontend/src/metabase/static-viz/register.js+++ b/frontend/src/metabase/static-viz/register.js@@ -8,6 +8,7 @@ import { ComboChart } from "metabase/visualizations/visualizations/ComboChart";import { Funnel } from "metabase/visualizations/visualizations/Funnel";import { LineChart } from "metabase/visualizations/visualizations/LineChart";import { PieChart } from "metabase/visualizations/visualizations/PieChart";+import Progress from "metabase/visualizations/visualizations/Progress";import RowChart from "metabase/visualizations/visualizations/RowChart";import { SankeyChart } from "metabase/visualizations/visualizations/SankeyChart";import { Scalar } from "metabase/visualizations/visualizations/Scalar";@@ -28,5 +29,6 @@ export const registerStaticVisualizations = () => {registerVisualization(PieChart);registerVisualization(SankeyChart);registerVisualization(RowChart);+ registerVisualization(Progress);setDefaultVisualization(Scalar);};diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker.jsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker.jsxindex 83fef7a4b71..69fdc151bec 100644--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker.jsx+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker.jsx@@ -16,6 +16,7 @@ import {} from "./ChartSettingFieldPicker.styled";import { ChartSettingSelect } from "./ChartSettingSelect";+const RIGHT_SECTION_PADDING = 16;const RIGHT_SECTION_BUTTON_WIDTH = 22;export const ChartSettingFieldPicker = ({@@ -86,7 +87,8 @@ export const ChartSettingFieldPicker = ({const rightSectionWidth =[!disabled, !!menuWidgetInfo, !!onRemove].filter(Boolean).length *- RIGHT_SECTION_BUTTON_WIDTH;+ RIGHT_SECTION_BUTTON_WIDTH ++ RIGHT_SECTION_PADDING;return (<ChartSettingFieldPickerRoot@@ -96,8 +98,7 @@ export const ChartSettingFieldPicker = ({align="center"><ChartSettingSelect- pl="sm"- pr="xs"+ pl={hasLeftSection ? "sm" : 0}w="100%"defaultDropdownOpened={autoOpenWhenUnset && value === undefined}options={options}@@ -170,7 +171,7 @@ export const ChartSettingFieldPicker = ({zIndex: "initial",},input: {- marginLeft: theme.spacing.xs,+ marginLeft: hasLeftSection ? theme.spacing.xs : 0,textOverflow: "ellipsis",fontWeight: "bold",diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingGoalInput.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingGoalInput.tsxnew file mode 100644index 00000000000..49cae682c5b--- /dev/null+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingGoalInput.tsx@@ -0,0 +1,117 @@+import { useMemo, useRef, useState } from "react";+import { t } from "ttag";++import { ActionIcon, Icon, Menu, NumberInput, TextInput } from "metabase/ui";+import { isNumeric } from "metabase-lib/v1/types/utils/isa";+import type { DatasetColumn } from "metabase-types/api";++interface ChartSettingGoalInputProps {+ id: string;+ value: number | string;+ onChange: (value: number | string) => void;+ columns?: DatasetColumn[];+ valueField?: string;+}++export const ChartSettingGoalInput = ({+ id,+ value,+ onChange,+ columns = [],+ valueField,+}: ChartSettingGoalInputProps) => {+ const [isPopoverOpen, setIsPopoverOpen] = useState(false);+ const numberInputRef = useRef<HTMLInputElement>(null);++ const numericColumns = useMemo(() => {+ if (!columns?.length) {+ return [];+ }+ return columns.filter(isNumeric).map((col) => ({+ value: col.name,+ label: col.display_name || col.name,+ }));+ }, [columns]);++ const isColumnReference =+ typeof value === "string" &&+ numericColumns.some((col) => col.value === value);++ const numericValue = typeof value === "number" ? value : 0;+ const availableColumns = numericColumns.filter(+ (col) => col.value !== valueField,+ );+ const hasNumericColumns = availableColumns.length > 0;++ const selectedColumn = isColumnReference+ ? numericColumns.find((col) => col.value === value)+ : null;++ const handleMenuItemSelect = (selectedValue: string | number) => {+ onChange(selectedValue);+ setIsPopoverOpen(false);+ if (typeof selectedValue === "number") {+ setTimeout(() => {+ numberInputRef.current?.focus();+ numberInputRef.current?.select();+ }, 0);+ }+ };++ const rightSection = hasNumericColumns ? (+ <Menu+ opened={isPopoverOpen}+ onChange={setIsPopoverOpen}+ position="bottom-end"+ withArrow+ >+ <Menu.Target>+ <ActionIcon c="text-medium" size="sm" radius="xl" p={0}>+ <Icon name="chevrondown" />+ </ActionIcon>+ </Menu.Target>+ <Menu.Dropdown miw={320}>+ <Menu.Item onClick={() => handleMenuItemSelect(numericValue)} fw="bold">+ {t`Custom value`}+ </Menu.Item>+ <Menu.Divider />+ {availableColumns.map((column) => (+ <Menu.Item+ key={column.value}+ onClick={() => handleMenuItemSelect(column.value)}+ fw="bold"+ >+ {column.label}+ </Menu.Item>+ ))}+ </Menu.Dropdown>+ </Menu>+ ) : null;++ if (isColumnReference) {+ return (+ <TextInput+ id={id}+ value={selectedColumn?.label || value}+ readOnly+ placeholder={selectedColumn?.label || value}+ fw="bold"+ rightSection={rightSection}+ rightSectionPointerEvents="all"+ />+ );+ }++ return (+ <NumberInput+ ref={numberInputRef}+ id={id}+ value={numericValue}+ onChange={(val) => onChange(val ?? 0)}+ placeholder={t`Enter goal value`}+ fw="bold"+ rightSection={rightSection}+ rightSectionPointerEvents="all"+ />+ );+};diff --git a/frontend/src/metabase/visualizations/visualizations/Progress/Progress.jsx b/frontend/src/metabase/visualizations/visualizations/Progress/Progress.jsxindex 59327a4a274..0c54a27c778 100644--- a/frontend/src/metabase/visualizations/visualizations/Progress/Progress.jsx+++ b/frontend/src/metabase/visualizations/visualizations/Progress/Progress.jsx@@ -1,23 +1,30 @@/* eslint-disable react/prop-types */import cx from "classnames";-import Color from "color";import { Component, createRef } from "react";import { t } from "ttag";-import _ from "underscore";import IconBorder from "metabase/common/components/IconBorder";import CS from "metabase/css/core/index.css";import { color } from "metabase/lib/colors";import { formatValue } from "metabase/lib/formatting";import { Icon } from "metabase/ui";+import { ChartSettingGoalInput } from "metabase/visualizations/components/settings/ChartSettingGoalInput";import { columnSettings } from "metabase/visualizations/lib/settings/column";+import { fieldSetting } from "metabase/visualizations/lib/settings/utils";import {getDefaultSize,getMinSize,} from "metabase/visualizations/shared/utils/sizes";import { isNumeric } from "metabase-lib/v1/types/utils/isa";-import { getValue } from "./utils";+import {+ calculateProgressMetrics,+ extractProgressValue,+ findProgressColumn,+ getGoalValue,+ getProgressColors,+ getProgressMessage,+} from "./utils";const BORDER_RADIUS = 5;const MAX_BAR_HEIGHT = 65;@@ -43,20 +50,41 @@ export default class Progress extends Component {static defaultSize = getDefaultSize("progress");static isSensible({ cols, rows }) {- return rows.length === 1 && cols.length === 1;+ return rows.length === 1 && cols.filter(isNumeric).length >= 1;}static checkRenderable([{- data: { cols, rows },+ data: { cols },},]) {- if (!isNumeric(cols[0])) {- throw new Error(t`Progress visualization requires a number.`);+ if (!cols.some(isNumeric)) {+ throw new Error(+ t`Progress visualization requires at least one numeric column.`,+ );}}static settings = {+ ...fieldSetting("progress.value", {+ get section() {+ return t`Display`;+ },+ get title() {+ return t`Value`;+ },+ fieldFilter: isNumeric,+ getDefault: ([+ {+ data: { cols },+ },+ ]) => cols.find(isNumeric)?.name || cols[0]?.name,+ getHidden: ([+ {+ data: { cols },+ },+ ]) => cols.filter(isNumeric).length <= 1,+ }),...columnSettings({getColumns: ([@@ -65,9 +93,12 @@ export default class Progress extends Component {},],settings,- ) => [- _.find(cols, (col) => col.name === settings["scalar.field"]) || cols[0],- ],+ ) => {+ const valueField = settings["progress.value"];+ const column = findProgressColumn(cols, valueField);+ return [column || cols[0]];+ },+ readDependencies: ["progress.value"],}),"progress.goal": {get section() {@@ -76,8 +107,27 @@ export default class Progress extends Component {get title() {return t`Goal`;},- widget: "number",+ widget: ChartSettingGoalInput,default: 0,+ isValid: ([{ data }], settings) => {+ const goalSetting = settings["progress.goal"];++ if (typeof goalSetting === "number") {+ return true;+ }++ if (typeof goalSetting === "string") {+ const column = data.cols.find((col) => col.name === goalSetting);+ return !!(column && isNumeric(column));+ }++ return false;+ },+ getProps: ([{ data }], settings) => ({+ columns: data.cols,+ valueField: settings["progress.value"],+ }),+ readDependencies: ["progress.value"],},"progress.color": {get section() {@@ -151,27 +201,25 @@ export default class Progress extends Component {visualizationIsClickable,} = this.props;- const value = getValue(rows);- const column = cols[0];- const goal = settings["progress.goal"] || 0;+ const valueField = settings["progress.value"];+ const column = findProgressColumn(cols, valueField);+ const columnIndex = column+ ? cols.findIndex((col) => col.name === column.name)+ : -1;- const mainColor = settings["progress.color"];- const lightColor = Color(mainColor).lighten(0.25).rgb().string();- const darkColor = Color(mainColor).darken(0.3).rgb().string();+ const value = extractProgressValue(rows, columnIndex);+ const goal = getGoalValue(settings["progress.goal"], cols, rows);- const progressColor = mainColor;- const restColor = value > goal ? darkColor : lightColor;- const arrowColor = value > goal ? darkColor : mainColor;+ const metrics = calculateProgressMetrics(value, goal);+ const { hasValidValue, hasValidGoal, barPercent, arrowPercent } = metrics;- const barPercent = Math.max(0, value < goal ? value / goal : goal / value);- const arrowPercent = Math.max(0, value < goal ? value / goal : 1);+ const mainColor = settings["progress.color"];+ const colors = getProgressColors(mainColor, value, goal);+ const progressColor = colors.foreground;+ const restColor = colors.background;+ const arrowColor = colors.pointer;- let barMessage;- if (value === goal) {- barMessage = t`Goal met`;- } else if (value > goal) {- barMessage = t`Goal exceeded`;- }+ const barMessage = getProgressMessage(metrics);const clicked = { value, column, settings };const isClickable = onVisualizationClick != null;@@ -203,7 +251,9 @@ export default class Progress extends Component {style={{ height: 20 }}><div ref={this.labelRef} style={{ position: "absolute" }}>- {formatValue(value, settings.column(column))}+ {hasValidValue+ ? formatValue(value, settings.column(column))+ : t`No data`}</div></div><div className={CS.relative} style={{ height: 10, marginBottom: 5 }}>@@ -260,10 +310,11 @@ export default class Progress extends Component {</div><div className={CS.mt1}><span className={CS.floatLeft}>0</span>- <span className={CS.floatRight}>{t`Goal ${formatValue(- goal,- settings.column(column),- )}`}</span>+ <span className={CS.floatRight}>+ {hasValidGoal+ ? t`Goal ${formatValue(goal, settings.column(column))}`+ : t`Goal: Not set`}+ </span></div></div></div>diff --git a/frontend/src/metabase/visualizations/visualizations/Progress/utils.ts b/frontend/src/metabase/visualizations/visualizations/Progress/utils.tsindex 1317ee308e2..3e85c06ba2d 100644--- a/frontend/src/metabase/visualizations/visualizations/Progress/utils.ts+++ b/frontend/src/metabase/visualizations/visualizations/Progress/utils.ts@@ -1,4 +1,11 @@-export const getValue = (rows: unknown[][]) => {+import Color from "color";+import { t } from "ttag";+import _ from "underscore";++import { isNumeric } from "metabase-lib/v1/types/utils/isa";+import type { DatasetColumn, RowValues } from "metabase-types/api";++export const getValue = (rows: RowValues[]) => {const rawValue = rows[0] && rows[0][0];if (rawValue === "Infinity") {@@ -11,3 +18,146 @@ export const getValue = (rows: unknown[][]) => {return rawValue;};++export const getGoalValue = (+ goalSetting: number | string,+ columns: DatasetColumn[],+ rows: RowValues[],+): number => {+ if (typeof goalSetting === "number") {+ return goalSetting;+ }++ if (typeof goalSetting === "string") {+ const columnIndex = columns.findIndex((col) => col.name === goalSetting);++ if (columnIndex !== -1 && rows[0]) {+ const rawValue = rows[0][columnIndex];+ if (rawValue === null || rawValue === undefined) {+ return 0;+ }+ if (rawValue === "Infinity") {+ return Infinity;+ }+ if (typeof rawValue === "number") {+ return rawValue;+ }+ }+ }++ return 0;+};++export const extractProgressValue = (+ rows: RowValues[],+ columnIndex: number,+): number => {+ if (rows[0] != null) {+ const rawValue = rows[0][columnIndex];+ if (rawValue === null || rawValue === undefined) {+ return 0;+ } else if (rawValue === "Infinity") {+ return Infinity;+ } else if (typeof rawValue === "number") {+ return rawValue;+ } else {+ return 0;+ }+ }+ return getValue(rows);+};++export const findProgressColumn = (+ cols: DatasetColumn[],+ valueField?: string,+): DatasetColumn | undefined => {+ if (valueField) {+ return _.find(cols, (col) => col.name === valueField);+ }+ return cols.find(isNumeric) || cols[0];+};++export interface ProgressMetrics {+ value: number;+ goal: number;+ hasValidValue: boolean;+ hasValidGoal: boolean;+ barPercent: number;+ arrowPercent: number;+}++export const calculateProgressMetrics = (+ value: number,+ goal: number,+): ProgressMetrics => {+ const hasValidValue = value !== null && value !== undefined && !isNaN(value);+ const hasValidGoal =+ goal !== null && goal !== undefined && !isNaN(goal) && goal >= 0;++ let barPercent = 0;+ let arrowPercent = 0;++ if (hasValidValue && hasValidGoal) {+ barPercent = barPercent =+ value === goal+ ? 1+ : Math.max(0, value < goal ? value / goal : goal / value);+ arrowPercent = Math.max(0, value < goal ? value / goal : 1);+ }++ return {+ value,+ goal,+ hasValidValue,+ hasValidGoal,+ barPercent,+ arrowPercent,+ };+};++export interface ProgressColors {+ main: string;+ light: string;+ dark: string;+ foreground: string;+ background: string;+ pointer: string;+}++export const getProgressColors = (+ mainColor: string,+ value: number,+ goal: number,+): ProgressColors => {+ const mainHex = Color(mainColor).hex();+ const light = Color(mainColor).lighten(0.25).hex();+ const dark = Color(mainColor).darken(0.3).hex();+ const isExceeded = value > goal;++ return {+ main: mainHex,+ light,+ dark,+ foreground: mainHex,+ background: isExceeded ? dark : light,+ pointer: isExceeded ? dark : mainHex,+ };+};++export const getProgressMessage = (metrics: ProgressMetrics): string => {+ const { value, goal, hasValidValue, hasValidGoal } = metrics;++ if (!hasValidValue && !hasValidGoal) {+ return t`No data available`;+ } else if (!hasValidValue) {+ return t`No value data`;+ } else if (!hasValidGoal) {+ return t`No goal set`;+ } else if (value === goal) {+ return t`Goal met`;+ } else if (value > goal) {+ return t`Goal exceeded`;+ }++ return "";+};diff --git a/frontend/src/metabase/visualizations/visualizations/Progress/utils.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/Progress/utils.unit.spec.tsindex 0e5677f50d6..48a1bc63223 100644--- a/frontend/src/metabase/visualizations/visualizations/Progress/utils.unit.spec.ts+++ b/frontend/src/metabase/visualizations/visualizations/Progress/utils.unit.spec.ts@@ -21,7 +21,7 @@ describe("Visualizations > Progress > utils", () => {valueTestCases.forEach(([input, output]) => {it(`should return ${output} for ${JSON.stringify(input)}`, () => {- expect(getValue(input as unknown[][])).toEqual(output);+ expect(getValue(input as any)).toEqual(output);});});});diff --git a/frontend/test/metabase/visualizations/visualizations/Progress/utils.unit.spec.ts b/frontend/test/metabase/visualizations/visualizations/Progress/utils.unit.spec.tsnew file mode 100644index 00000000000..6d24658b945--- /dev/null+++ b/frontend/test/metabase/visualizations/visualizations/Progress/utils.unit.spec.ts@@ -0,0 +1,355 @@+import { t } from "ttag";++import {+ type ProgressMetrics,+ calculateProgressMetrics,+ extractProgressValue,+ findProgressColumn,+ getGoalValue,+ getProgressColors,+ getProgressMessage,+ getValue,+} from "metabase/visualizations/visualizations/Progress/utils";+import type { DatasetColumn, RowValues } from "metabase-types/api";+import { createMockColumn } from "metabase-types/api/mocks";++const mockColumns: DatasetColumn[] = [+ createMockColumn({+ name: "count",+ display_name: "Count",+ base_type: "type/Integer",+ }),+ createMockColumn({+ name: "total",+ display_name: "Total",+ base_type: "type/Float",+ }),+ createMockColumn({+ name: "name",+ display_name: "Name",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "average",+ display_name: "Average",+ base_type: "type/Float",+ }),+];++describe("getValue", () => {+ it("should return the first row, first column value", () => {+ const rows: RowValues[] = [+ [42, "test"],+ [100, "other"],+ ];+ expect(getValue(rows)).toBe(42);+ });++ it("should return 0 for non-numeric values", () => {+ const rows: RowValues[] = [["not a number", "test"]];+ expect(getValue(rows)).toBe(0);+ });++ it("should handle Infinity", () => {+ const rows: RowValues[] = [["Infinity", "test"]];+ expect(getValue(rows)).toBe(Infinity);+ });++ it("should return 0 for empty rows", () => {+ const rows: RowValues[] = [];+ expect(getValue(rows)).toBe(0);+ });++ it("should return 0 for null values", () => {+ const rows: RowValues[] = [[null, "test"]];+ expect(getValue(rows)).toBe(0);+ });+});++describe("getGoalValue", () => {+ const rows: RowValues[] = [[10, 100.5, "test", 25.0]];++ it("should return the number when goal is numeric", () => {+ expect(getGoalValue(50, mockColumns, rows)).toBe(50);+ expect(getGoalValue(0, mockColumns, rows)).toBe(0);+ expect(getGoalValue(-10, mockColumns, rows)).toBe(-10);+ });++ it("should return column value when goal is a column name", () => {+ expect(getGoalValue("count", mockColumns, rows)).toBe(10);+ expect(getGoalValue("total", mockColumns, rows)).toBe(100.5);+ expect(getGoalValue("average", mockColumns, rows)).toBe(25.0);+ });++ it("should return 0 for non-existent column names", () => {+ expect(getGoalValue("nonexistent", mockColumns, rows)).toBe(0);+ });++ it("should handle null column values", () => {+ const rowsWithNull: RowValues[] = [[10, null, "test", 25.0]];+ expect(getGoalValue("total", mockColumns, rowsWithNull)).toBe(0);+ });++ it("should handle Infinity in columns", () => {+ const rowsWithInfinity: RowValues[] = [[10, "Infinity", "test", 25.0]];+ expect(getGoalValue("total", mockColumns, rowsWithInfinity)).toBe(Infinity);+ });++ it("should return 0 for invalid goal types", () => {+ expect(getGoalValue(null as any, mockColumns, rows)).toBe(0);+ expect(getGoalValue(undefined as any, mockColumns, rows)).toBe(0);+ });+});++describe("extractProgressValue", () => {+ const rows: RowValues[] = [[10, 100.5, "test", 25.0]];++ it("should extract value from specified column index", () => {+ expect(extractProgressValue(rows, 0)).toBe(10);+ expect(extractProgressValue(rows, 1)).toBe(100.5);+ expect(extractProgressValue(rows, 3)).toBe(25.0);+ });++ it("should handle null values in columns", () => {+ const rowsWithNull: RowValues[] = [[null, 100.5, "test", 25.0]];+ expect(extractProgressValue(rowsWithNull, 0)).toBe(0);+ });++ it("should handle Infinity values", () => {+ const rowsWithInfinity: RowValues[] = [["Infinity", 100.5, "test", 25.0]];+ expect(extractProgressValue(rowsWithInfinity, 0)).toBe(Infinity);+ });++ it("should handle empty rows", () => {+ expect(extractProgressValue([], 0)).toBe(0);+ });++ it("should handle non-numeric values", () => {+ const rowsWithText: RowValues[] = [["not a number", 100.5, "test", 25.0]];+ expect(extractProgressValue(rowsWithText, 0)).toBe(0);+ });+});++describe("findProgressColumn", () => {+ it("should find column by valueField when provided", () => {+ const result = findProgressColumn(mockColumns, "total");+ expect(result).toBe(mockColumns[1]);+ });++ it("should return first numeric column when no valueField", () => {+ const result = findProgressColumn(mockColumns);+ expect(result).toBe(mockColumns[0]); // "count" is first numeric+ });++ it("should fallback to first column when no numeric columns", () => {+ const textOnlyColumns: DatasetColumn[] = [+ createMockColumn({+ name: "name1",+ display_name: "Name 1",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "name2",+ display_name: "Name 2",+ base_type: "type/Text",+ }),+ ];+ const result = findProgressColumn(textOnlyColumns);+ expect(result).toBe(textOnlyColumns[0]);+ });++ it("should return undefined for non-existent valueField", () => {+ const result = findProgressColumn(mockColumns, "nonexistent");+ expect(result).toBeUndefined();+ });++ it("should handle empty columns array", () => {+ const result = findProgressColumn([]);+ expect(result).toBeUndefined();+ });+});++describe("calculateProgressMetrics", () => {+ it("should calculate metrics for value under goal", () => {+ const result = calculateProgressMetrics(25, 100);+ expect(result).toEqual({+ value: 25,+ goal: 100,+ hasValidValue: true,+ hasValidGoal: true,+ barPercent: 0.25,+ arrowPercent: 0.25,+ });+ });++ it("should calculate metrics for value over goal", () => {+ const result = calculateProgressMetrics(150, 100);+ expect(result).toEqual({+ value: 150,+ goal: 100,+ hasValidValue: true,+ hasValidGoal: true,+ barPercent: 100 / 150, // goal / value when exceeded+ arrowPercent: 1, // Maxed at 1 when exceeded+ });+ });++ it("should calculate metrics for value equal to goal", () => {+ const result = calculateProgressMetrics(100, 100);+ expect(result).toEqual({+ value: 100,+ goal: 100,+ hasValidValue: true,+ hasValidGoal: true,+ barPercent: 1,+ arrowPercent: 1,+ });+ });++ it("should handle invalid values", () => {+ const result = calculateProgressMetrics(NaN, 100);+ expect(result).toEqual({+ value: NaN,+ goal: 100,+ hasValidValue: false,+ hasValidGoal: true,+ barPercent: 0,+ arrowPercent: 0,+ });+ });++ it("should handle invalid goals", () => {+ const result = calculateProgressMetrics(50, NaN);+ expect(result).toEqual({+ value: 50,+ goal: NaN,+ hasValidValue: true,+ hasValidGoal: false,+ barPercent: 0,+ arrowPercent: 0,+ });+ });++ it("should handle negative goals as invalid", () => {+ const result = calculateProgressMetrics(50, -10);+ expect(result).toEqual({+ value: 50,+ goal: -10,+ hasValidValue: true,+ hasValidGoal: false,+ barPercent: 0,+ arrowPercent: 0,+ });+ });++ it("should accept zero as valid goal", () => {+ const result = calculateProgressMetrics(50, 0);+ expect(result).toEqual({+ value: 50,+ goal: 0,+ hasValidValue: true,+ hasValidGoal: true,+ barPercent: 0, // goal / value = 0 / 50 = 0+ arrowPercent: 1, // value > goal, so maxed at 1+ });+ });++ it("should handle null and undefined values", () => {+ expect(calculateProgressMetrics(null as any, 100).hasValidValue).toBe(+ false,+ );+ expect(calculateProgressMetrics(undefined as any, 100).hasValidValue).toBe(+ false,+ );+ expect(calculateProgressMetrics(50, null as any).hasValidGoal).toBe(false);+ expect(calculateProgressMetrics(50, undefined as any).hasValidGoal).toBe(+ false,+ );+ });+});++describe("getProgressColors", () => {+ it("should return different colors when goal is exceeded", () => {+ const result = getProgressColors("#3366ff", 150, 100);++ expect(result.background).toBe(result.dark);+ expect(result.pointer).toBe(result.dark);+ });++ it("should handle named colors and convert to hex", () => {+ const result = getProgressColors("red", 50, 100);++ expect(result.main).toBe("#FF0000");+ expect(result.foreground).toBe("#FF0000");+ });++ it("should handle RGB colors and convert to hex", () => {+ const result = getProgressColors("rgb(255, 0, 0)", 50, 100);++ expect(result.main).toBe("#FF0000");+ expect(result.foreground).toBe("#FF0000");+ });++ it("should handle HSL colors and convert to hex", () => {+ const result = getProgressColors("hsl(0, 100%, 50%)", 50, 100);++ expect(result.main).toBe("#FF0000");+ expect(result.foreground).toBe("#FF0000");+ });+});++describe("getProgressMessage", () => {+ const createMetrics = (+ value: number,+ goal: number,+ hasValidValue = true,+ hasValidGoal = true,+ ): ProgressMetrics => ({+ value,+ goal,+ hasValidValue,+ hasValidGoal,+ barPercent: 0,+ arrowPercent: 0,+ });++ it("should return 'Goal met' when value equals goal", () => {+ const metrics = createMetrics(100, 100);+ expect(getProgressMessage(metrics)).toBe(t`Goal met`);+ });++ it("should return 'Goal exceeded' when value is greater than goal", () => {+ const metrics = createMetrics(150, 100);+ expect(getProgressMessage(metrics)).toBe(t`Goal exceeded`);+ });++ it("should return empty string when value is less than goal", () => {+ const metrics = createMetrics(75, 100);+ expect(getProgressMessage(metrics)).toBe("");+ });++ it("should return 'No data available' when both value and goal are invalid", () => {+ const metrics = createMetrics(NaN, NaN, false, false);+ expect(getProgressMessage(metrics)).toBe(t`No data available`);+ });++ it("should return 'No value data' when only value is invalid", () => {+ const metrics = createMetrics(NaN, 100, false, true);+ expect(getProgressMessage(metrics)).toBe(t`No value data`);+ });++ it("should return 'No goal set' when only goal is invalid", () => {+ const metrics = createMetrics(75, NaN, true, false);+ expect(getProgressMessage(metrics)).toBe(t`No goal set`);+ });++ it("should prioritize 'No data available' over other messages", () => {+ const metrics = createMetrics(100, 100, false, false); // Both invalid but values happen to be equal+ expect(getProgressMessage(metrics)).toBe(t`No data available`);+ });++ it("should handle zero values correctly", () => {+ const metrics = createMetrics(0, 0);+ expect(getProgressMessage(metrics)).toBe(t`Goal met`);+ });+});diff --git a/resources/frontend_shared/static_viz_interface.js b/resources/frontend_shared/static_viz_interface.jsindex e55da5471dd..be8554372b3 100644--- a/resources/frontend_shared/static_viz_interface.js+++ b/resources/frontend_shared/static_viz_interface.js@@ -36,17 +36,6 @@ function funnel(data, settings, tokenFeatures) {});}-/**- * @deprecated use javascript_visualization instead- */-function progress(data, settings, instanceColors, tokenFeatures) {- return StaticViz.LegacyRenderChart("progress", {- data: JSON.parse(data),- settings: JSON.parse(settings),- colors: JSON.parse(instanceColors),- tokenFeatures: JSON.parse(tokenFeatures),- });-}function javascript_visualization(rawSeries, dashcardSettings, options) {const content = StaticViz.RenderChart(diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.cljindex 0d28cd855bf..1e8845cf05e 100644--- a/src/metabase/channel/render/body.clj+++ b/src/metabase/channel/render/body.clj@@ -329,33 +329,6 @@(DecimalFormat. base))](.format fmt value))))-(mu/defmethod render :progress :- ::RenderedPartCard- [_chart-type- render-type- _timezone-id- _card- _dashcard- {:keys [cols rows viz-settings] :as _data}]- (let [value (ffirst rows)- goal (:progress.goal viz-settings)- color (:progress.color viz-settings)- settings (assoc- (->js-viz (first cols) (first cols) viz-settings)- :color color)- ;; ->js-viz fills in our :x but we actually want that under :format key- settings (assoc settings :format (:x settings))- image-bundle (image-bundle/make-image-bundle- render-type- (js.svg/progress value goal settings))]- {:attachments- (when image-bundle- (image-bundle/image-bundle->attachment image-bundle))-- :content- [:div- [:img {:style (style/style {:display :block :width :100%})- :src (:image-src image-bundle)}]]}))-(defn- add-dashcard-timeline-events"If there's a timeline associated with this card, add its events in."[card-with-data]diff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.cljindex d8da16a0fd6..7068caea770 100644--- a/src/metabase/channel/render/card.clj+++ b/src/metabase/channel/render/card.clj@@ -116,13 +116,13 @@(chart-type :scalar "result has one row and one column")(#{:scalar- :progress:gauge:table:funnel} display-type)(chart-type display-type "display-type is %s" display-type)(#{:smartscalar+ :progress:sankey:scalar:piediff --git a/src/metabase/util/ui_logic.clj b/src/metabase/util/ui_logic.cljindex e504a0c9fdf..3d092d7d25f 100644--- a/src/metabase/util/ui_logic.clj+++ b/src/metabase/util/ui_logic.clj@@ -119,14 +119,57 @@"For a given resultset, return the index of the column that should be used for the goal comparison. This can comefrom the visualization settings if the column is specified, or from our default column logic"[card result]- (if-let [user-specified-rowfn (y-axis-rowfn card result)]- user-specified-rowfn- (when-let [default-col-index (default-goal-column-index card result)]+ (let [user-specified-rowfn (y-axis-rowfn card result)+ default-col-index (default-goal-column-index card result)+ progress-value-col (when (= :progress (:display card))+ (get-in card [:visualization_settings :progress.value]))+ progress-col-index (when progress-value-col+ (column-name->index progress-value-col result))+ first-numeric-col-index (when (and (= :progress (:display card))+ (not progress-col-index))+ (first (keep-indexed (fn [idx col]+ (when (isa? (:base_type col) :type/Number)+ idx))+ (:cols result))))]+ (cond+ user-specified-rowfn+ user-specified-rowfn++ progress-col-index(fn [row]- (nth row default-col-index)))))+ (nth row progress-col-index))++ first-numeric-col-index+ (fn [row]+ (nth row first-numeric-col-index))++ default-col-index+ (fn [row]+ (nth row default-col-index))++ :else nil)))++(defn- extract-goal-value-from-column+ "Extracts goal value from a column reference, similar to frontend getGoalValue"+ [goal-setting columns rows]+ (when (string? goal-setting)+ (let [column-index (->> columns+ (map-indexed vector)+ (filter #(= goal-setting (:name (second %))))+ first+ first)]+ (when (and column-index (seq rows))+ (let [raw-value (nth (first rows) column-index nil)]+ (cond+ (nil? raw-value) 0+ (= "Infinity" raw-value) ##Inf+ (number? raw-value) raw-value+ :else 0))))))(defn find-goal-value- "The goal value can come from a progress goal or a graph goal_value depending on it's type"+ "The goal value can come from a progress goal or a graph goal_value depending on it's type.+ For progress charts, the goal can be either a number or a column reference.+ Matches the frontend behavior: invalid goals fallback to default value (0)."[result](case (get-in result [:card :display])@@ -134,6 +177,20 @@(get-in result [:card :visualization_settings :graph.goal_value]):progress- (get-in result [:card :visualization_settings :progress.goal])+ (let [goal-setting (get-in result [:card :visualization_settings :progress.goal])+ columns (get-in result [:result :data :cols])+ rows (get-in result [:result :data :rows])]+ (cond+ (number? goal-setting)+ goal-setting++ (string? goal-setting)+ (if-let [column (->> columns (filter #(= goal-setting (:name %))) first)]+ (if (isa? (:base_type column) :type/Number)+ (extract-goal-value-from-column goal-setting columns rows)+ 0)+ 0)++ :else 0))nil))diff --git a/test/metabase/channel/render/body_test.clj b/test/metabase/channel/render/body_test.cljindex 44cb19044d0..1d9f68d6f94 100644--- a/test/metabase/channel/render/body_test.clj+++ b/test/metabase/channel/render/body_test.clj@@ -590,23 +590,6 @@:slice-els-colours slice-elements:total-els-text total-elements})))))))))))-(deftest render-progress- (let [col [{:name "NumPurchased",- :display_name "NumPurchased",- :base_type :type/Integer- :semantic_type nil}]- render (fn [rows]- (body/render :progress :inline pacific-tz- render.tu/test-card- nil- {:cols col :rows rows}))]- (testing "Renders without error"- (let [rendered-info (render [[25]])]- (is (has-inline-image? rendered-info))))- (testing "Renders negative value without error"- (let [rendered-info (render [[-25]])]- (is (has-inline-image? rendered-info))))))-(deftest ^:parallel format-percentage-test(are [value expected] (= expected(body/format-percentage 12345.4321 value))diff --git a/test/metabase/channel/render/card_test.clj b/test/metabase/channel/render/card_test.cljindex 3d0a56f7e1d..40c21627fdb 100644--- a/test/metabase/channel/render/card_test.clj+++ b/test/metabase/channel/render/card_test.clj@@ -107,7 +107,7 @@(deftest ^:parallel detect-pulse-chart-type-test-5(testing "Progress charts are correctly identified"- (is (= :progress+ (is (= :javascript_visualization(channel.render/detect-pulse-chart-type {:display :progress}{}{:cols [{:base_type :type/Number}]@@ -137,7 +137,6 @@:rows [["A" 2]["B" 3]]})):funnel- :progress:table)))(deftest ^:parallel detect-pulse-chart-type-test-8diff --git a/test/metabase/channel/render/js/svg_test.clj b/test/metabase/channel/render/js/svg_test.cljindex 55f4415894c..aa09ae56876 100644--- a/test/metabase/channel/render/js/svg_test.clj+++ b/test/metabase/channel/render/js/svg_test.clj@@ -6,14 +6,10 @@the svg png renderer does not understand nested html elements so we ensure that there are no divs, spans, etc in theresulting svg."(:require- [clojure.set :as set][clojure.test :refer :all]- [metabase.channel.render.js.engine :as js.engine]- [metabase.channel.render.js.svg :as js.svg]- [metabase.util.json :as json])+ [metabase.channel.render.js.svg :as js.svg])(:import(org.apache.batik.anim.dom SVGOMDocument)- (org.graalvm.polyglot Value)(org.w3c.dom Element Node)))(set! *warn-on-reflection* true)@@ -52,49 +48,6 @@(is (= "0.0"(.getAttribute line "fill-opacity")))))-(defn- document-tag-seq [^SVGOMDocument document]- (map #(.getNodeName ^Node %)- (tree-seq #(instance? Element %)- (fn [^Node node]- (let [children (.getChildNodes node)]- (reduce (fn [cs i] (conj cs (.item children i)))- [] (range (.getLength children)))))- (.getDocumentElement document))))--(defn- normal-svg-elements [tag-set]- (set/subset? #{"svg" "g"} tag-set))--(defn- no-html-elements [tag-set]- (= #{} (set/intersection #{"div" "span" "p"} tag-set)))--(defn- validate-svg-string [chart svg-string]- (let [tag-seq (-> svg-string parse-svg document-tag-seq)- tag-set (set tag-seq)]- (testing (str chart " String is valid")- (is (string? svg-string) "Svg did not return a string"))- (testing " String contains normal svg elements"- (is (normal-svg-elements tag-set) "Did not contain normal svg elements #{svg g line}"))- (testing (str chart "String cannot contain html elements as svg renderer errors")- (is (no-html-elements tag-set) (str "Contained html elements: "- (set/intersection #{"div" "span" "p"}))))))--(deftest ^:parallel progress-test- (let [value 1234- goal 1337- settings {:color "#333333"}]- (testing "It returns bytes"- (let [svg-bytes (js.svg/progress value goal settings)]- (is (bytes? svg-bytes))))- (js.svg/with-static-viz-context context- (let [svg-string (.asString ^Value (js.engine/execute-fn-name- context- "progress"- (json/encode {:value value :goal goal})- (json/encode settings)- (json/encode {})- (json/encode {})))]- (validate-svg-string :progress svg-string)))))-(deftest ^:parallel parse-svg-sanitizes-characters-test(testing "Characters discouraged or not permitted by the xml 1.0 specification are removed. (#"(#'js.svg/parse-svg-stringdiff --git a/test/metabase/notification/payload/impl/card_test.clj b/test/metabase/notification/payload/impl/card_test.cljindex 250a1d762e9..aba8e977adf 100644--- a/test/metabase/notification/payload/impl/card_test.clj+++ b/test/metabase/notification/payload/impl/card_test.clj@@ -257,40 +257,53 @@(is (= 1 (count messages)))(is (= 0 (count messages)))))}))))))-(deftest ^:parallel goal-met-test- (let [alert-above-pulse {:send_condition "goal_above"}- alert-below-pulse {:send_condition "goal_below"}- progress-result (fn [val] {:card {:display :progress- :visualization_settings {:progress.goal 5}}- :result {:data {:rows [[val]]}}})- timeseries-result (fn [val] {:card {:display :bar- :visualization_settings {:graph.goal_value 5}}- :result {:data {:cols [{:source :breakout}- {:name "avg"- :source :aggregation- :base_type :type/Integer- :effective-type :type/Integer- :semantic_type :type/Quantity}]- :rows [["2021-01-01T00:00:00Z" val]]}}})- goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)]- (testing "Progress bar"- (testing "alert above"- (testing "value below goal" (is (= false (goal-met? alert-above-pulse (progress-result 4)))))- (testing "value equals goal" (is (true? (goal-met? alert-above-pulse (progress-result 5)))))- (testing "value above goal" (is (true? (goal-met? alert-above-pulse (progress-result 6))))))- (testing "alert below"- (testing "value below goal" (is (true? (goal-met? alert-below-pulse (progress-result 4)))))- (testing "value equals goal (#10899)" (is (= false (goal-met? alert-below-pulse (progress-result 5)))))- (testing "value above goal" (is (= false (goal-met? alert-below-pulse (progress-result 6)))))))- (testing "Timeseries"- (testing "alert above"- (testing "value below goal" (is (= false (goal-met? alert-above-pulse (timeseries-result 4)))))- (testing "value equals goal" (is (true? (goal-met? alert-above-pulse (timeseries-result 5)))))- (testing "value above goal" (is (true? (goal-met? alert-above-pulse (timeseries-result 6))))))- (testing "alert below"- (testing "value below goal" (is (true? (goal-met? alert-below-pulse (timeseries-result 4)))))- (testing "value equals goal" (is (= false (goal-met? alert-below-pulse (timeseries-result 5)))))- (testing "value above goal" (is (= false (goal-met? alert-below-pulse (timeseries-result 6)))))))))+(defn- progress-result [val]+ {:card {:display :progress+ :visualization_settings {:progress.goal 5}}+ :result {:data {:rows [[val]]}}})++(defn- timeseries-result [val]+ {:card {:display :bar+ :visualization_settings {:graph.goal_value 5}}+ :result {:data {:cols [{:source :breakout}+ {:name "avg"+ :source :aggregation+ :base_type :type/Integer+ :effective-type :type/Integer+ :semantic_type :type/Quantity}]+ :rows [["2021-01-01T00:00:00Z" val]]}}})++(deftest ^:parallel goal-met-progress-bar-alert-above-test+ (testing "Progress bar with alert above"+ (let [alert-above-pulse {:send_condition "goal_above"}+ goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)]+ (testing "value below goal" (is (= false (goal-met? alert-above-pulse (progress-result 4)))))+ (testing "value equals goal" (is (true? (goal-met? alert-above-pulse (progress-result 5)))))+ (testing "value above goal" (is (true? (goal-met? alert-above-pulse (progress-result 6))))))))++(deftest ^:parallel goal-met-progress-bar-alert-below-test+ (testing "Progress bar with alert below"+ (let [alert-below-pulse {:send_condition "goal_below"}+ goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)]+ (testing "value below goal" (is (true? (goal-met? alert-below-pulse (progress-result 4)))))+ (testing "value equals goal (#10899)" (is (= false (goal-met? alert-below-pulse (progress-result 5)))))+ (testing "value above goal" (is (= false (goal-met? alert-below-pulse (progress-result 6))))))))++(deftest ^:parallel goal-met-timeseries-alert-above-test+ (testing "Timeseries with alert above"+ (let [alert-above-pulse {:send_condition "goal_above"}+ goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)]+ (testing "value below goal" (is (= false (goal-met? alert-above-pulse (timeseries-result 4)))))+ (testing "value equals goal" (is (true? (goal-met? alert-above-pulse (timeseries-result 5)))))+ (testing "value above goal" (is (true? (goal-met? alert-above-pulse (timeseries-result 6))))))))++(deftest ^:parallel goal-met-timeseries-alert-below-test+ (testing "Timeseries with alert below"+ (let [alert-below-pulse {:send_condition "goal_below"}+ goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)]+ (testing "value below goal" (is (true? (goal-met? alert-below-pulse (timeseries-result 4)))))+ (testing "value equals goal" (is (= false (goal-met? alert-below-pulse (timeseries-result 5)))))+ (testing "value above goal" (is (= false (goal-met? alert-below-pulse (timeseries-result 6))))))))(deftest send-condition-above-goal-test(testing "skip is the goal is not met"@@ -612,3 +625,30 @@:filters nil}}(mt/latest-audit-log-entry :alert-send (:id notification)))))))))++(deftest ^:parallel progress-value-column-test+ (testing "Progress charts should use progress.value column instead of first column"+ (let [goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)+ notification-card {:send_condition "goal_above"}+ card-part {:card {:display :progress+ :visualization_settings {:progress.value "actual_value"+ :progress.goal "Target"}}+ :result {:data {:cols [{:name "ignore_me" :base_type :type/Integer}+ {:name "actual_value" :base_type :type/Integer}+ {:name "Target" :base_type :type/Integer}]+ :rows [[999 120 100]]}}}]+ (is (true? (goal-met? notification-card card-part))+ "Should return true when actual_value (120) >= Target (100)"))))++(deftest ^:parallel progress-value-fallback-test+ (testing "Progress charts should fall back to first numeric column when no progress.value is set"+ (let [goal-met? (requiring-resolve 'metabase.notification.payload.impl.card/goal-met?)+ notification-card {:send_condition "goal_above"}+ card-part {:card {:display :progress+ :visualization_settings {:progress.goal "Target"}}+ :result {:data {:cols [{:name "text_col" :base_type :type/Text}+ {:name "numeric_col" :base_type :type/Integer}+ {:name "Target" :base_type :type/Integer}]+ :rows [["text" 120 100]]}}}]+ (is (true? (goal-met? notification-card card-part))+ "Should return true when first numeric column (120) >= Target (100)"))))diff --git a/test/metabase/util/ui_logic_test.clj b/test/metabase/util/ui_logic_test.cljnew file mode 100644index 00000000000..4b5b6ffe99d--- /dev/null+++ b/test/metabase/util/ui_logic_test.clj@@ -0,0 +1,78 @@+(ns metabase.util.ui-logic-test+ (:require+ [clojure.test :refer :all]+ [metabase.util.ui-logic :as ui-logic]))++(deftest ^:parallel find-goal-value-with-numeric-goal-test+ (testing "Progress chart goal value extraction with numeric goal"+ (let [result {:card {:display :progress+ :visualization_settings {:progress.goal 100}}+ :result {:data {:cols []+ :rows []}}}]+ (is (= 100 (ui-logic/find-goal-value result))))))++(deftest ^:parallel find-goal-value-with-column-reference-numeric-test+ (testing "Progress chart goal value extraction with column reference that exists and is numeric"+ (let [result {:card {:display :progress+ :visualization_settings {:progress.goal "target_column"}}+ :result {:data {:cols [{:name "value_column" :base_type :type/Integer}+ {:name "target_column" :base_type :type/Float}]+ :rows [[50 75.5]]}}}]+ (is (= 75.5 (ui-logic/find-goal-value result))))))++(deftest ^:parallel find-goal-value-with-column-reference-non-numeric-test+ (testing "Progress chart goal value extraction with column reference that exists but is not numeric"+ (let [result {:card {:display :progress+ :visualization_settings {:progress.goal "text_column"}}+ :result {:data {:cols [{:name "value_column" :base_type :type/Integer}+ {:name "text_column" :base_type :type/Text}]+ :rows [[50 "not a number"]]}}}]+ (is (= 0 (ui-logic/find-goal-value result))))))++(deftest ^:parallel find-goal-value-with-nonexistent-column-test+ (testing "Progress chart goal value extraction with column reference that doesn't exist"+ (let [result {:card {:display :progress+ :visualization_settings {:progress.goal "nonexistent_column"}}+ :result {:data {:cols [{:name "value_column" :base_type :type/Integer}]+ :rows [[50]]}}}]+ (is (= 0 (ui-logic/find-goal-value result))))))++(deftest ^:parallel find-goal-value-with-nil-goal-test+ (testing "Progress chart goal value extraction with nil goal setting"+ (let [result {:card {:display :progress+ :visualization_settings {:progress.goal nil}}+ :result {:data {:cols []+ :rows []}}}]+ (is (= 0 (ui-logic/find-goal-value result))))))++(deftest ^:parallel find-goal-value-with-no-goal-test+ (testing "Progress chart goal value extraction with no goal setting"+ (let [result {:card {:display :progress+ :visualization_settings {}}+ :result {:data {:cols []+ :rows []}}}]+ (is (= 0 (ui-logic/find-goal-value result))))))++(deftest ^:parallel extract-goal-value-from-column-with-valid-data-test+ (testing "Extract goal value from column with valid column and data"+ (let [columns [{:name "value"} {:name "target"}]+ rows [[100 200]]]+ (is (= 200 (#'ui-logic/extract-goal-value-from-column "target" columns rows))))))++(deftest ^:parallel extract-goal-value-from-column-with-infinity-test+ (testing "Extract goal value from column with infinity value"+ (let [columns [{:name "value"} {:name "target"}]+ rows [[100 "Infinity"]]]+ (is (= ##Inf (#'ui-logic/extract-goal-value-from-column "target" columns rows))))))++(deftest ^:parallel extract-goal-value-from-column-with-nil-test+ (testing "Extract goal value from column with nil value"+ (let [columns [{:name "value"} {:name "target"}]+ rows [[100 nil]]]+ (is (= 0 (#'ui-logic/extract-goal-value-from-column "target" columns rows))))))++(deftest ^:parallel extract-goal-value-from-column-with-no-rows-test+ (testing "Extract goal value from column with no rows"+ (let [columns [{:name "value"} {:name "target"}]+ rows []]+ (is (nil? (#'ui-logic/extract-goal-value-from-column "target" columns rows))))))