You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by sb...@apache.org on 2026/09/10 17:49:18 UTC

(superset) branch master updated: feat: add conditional formating to CountryMap plugin (#42941)

This is an automated email from the ASF dual-hosted git repository.

SBIN2010 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new b20ad093910 feat: add conditional formating to CountryMap plugin (#42941)
b20ad093910 is described below

commit b20ad093910911fac7a10559c8bc2ed2c22eada4
Author: SBIN2010 <Sb...@mail.ru>
AuthorDate: Thu Sep 10 20:49:10 2026 +0300

    feat: add conditional formating to CountryMap plugin (#42941)
---
 .../plugin-chart-country-map/src/CountryMap.ts     |  16 +-
 .../plugin-chart-country-map/src/controlPanel.ts   |  43 ++++++
 .../plugin-chart-country-map/src/transformProps.ts |   5 +
 .../test/CountryMap.test.tsx                       | 168 +++++++++++++++++++++
 .../test/transformProps.test.ts                    |  27 ++++
 .../ConditionalFormattingControl.tsx               |   3 +
 .../FormattingPopover.tsx                          |   2 +
 .../FormattingPopoverContent.test.tsx              |  80 +++++++++-
 .../FormattingPopoverContent.tsx                   |  41 ++++-
 .../controls/ConditionalFormattingControl/types.ts |  10 ++
 10 files changed, 387 insertions(+), 8 deletions(-)

diff --git a/superset-frontend/plugins/plugin-chart-country-map/src/CountryMap.ts b/superset-frontend/plugins/plugin-chart-country-map/src/CountryMap.ts
index 048f92c7a81..7a8768d70aa 100644
--- a/superset-frontend/plugins/plugin-chart-country-map/src/CountryMap.ts
+++ b/superset-frontend/plugins/plugin-chart-country-map/src/CountryMap.ts
@@ -28,6 +28,7 @@ import {
   ValueFormatter,
   getSequentialSchemeRegistry,
 } from '@superset-ui/core';
+import { ColorFormatters } from '@superset-ui/chart-controls';
 import countries, { countryOptions } from './countries';
 
 /**
@@ -81,6 +82,7 @@ interface CountryMapProps {
     };
   };
   entity?: string;
+  formatters?: ColorFormatters;
 }
 
 const maps: Record<string, GeoData> = {};
@@ -105,6 +107,7 @@ function CountryMap(element: HTMLElement, props: CountryMapProps) {
     emitCrossFilters,
     onContextMenu,
     setDataMask,
+    formatters,
   } = props;
 
   const container = element;
@@ -120,16 +123,27 @@ function CountryMap(element: HTMLElement, props: CountryMapProps) {
   const colorScale = CategoricalColorNamespace.getScale(colorScheme);
 
   const colorMap: Record<string, string> = {};
+  const conditionalColorByIso: Record<string, string> = {};
   data.forEach(d => {
     colorMap[d.country_id] = colorScheme
       ? colorScale(d.country_id, sliceId)
       : (linearColorScale(d.metric) ?? '');
+
+    if (formatters?.length) {
+      for (const colorFormatter of formatters) {
+        const cfColor = colorFormatter.getColorFromValue(d.metric);
+        if (cfColor) {
+          conditionalColorByIso[d.country_id] = cfColor;
+          break;
+        }
+      }
+    }
   });
 
   const colorFn = (feature: GeoFeature): string => {
     if (!feature?.properties) return '#d9d9d9';
     const iso = feature.properties.ISO;
-    return colorMap[iso] || '#d9d9d9';
+    return conditionalColorByIso[iso] || colorMap[iso] || '#d9d9d9';
   };
 
   // Check if dashboard is in edit mode
diff --git a/superset-frontend/plugins/plugin-chart-country-map/src/controlPanel.ts b/superset-frontend/plugins/plugin-chart-country-map/src/controlPanel.ts
index 16b923be539..fb5e2d9eea8 100644
--- a/superset-frontend/plugins/plugin-chart-country-map/src/controlPanel.ts
+++ b/superset-frontend/plugins/plugin-chart-country-map/src/controlPanel.ts
@@ -23,8 +23,10 @@ import {
   D3_FORMAT_OPTIONS,
   D3_FORMAT_DOCS,
   getStandardizedControls,
+  Dataset,
 } from '@superset-ui/chart-controls';
 import { countryOptions } from './countries';
+import { GenericDataType } from '@apache-superset/core/common';
 
 const config: ControlPanelConfig = {
   controlPanelSections: [
@@ -71,6 +73,47 @@ const config: ControlPanelConfig = {
         ],
         ['currency_format'],
         ['linear_color_scheme'],
+        [
+          {
+            name: 'conditional_formatting',
+            config: {
+              type: 'ConditionalFormattingControl',
+              renderTrigger: true,
+              label: t('Custom conditional formatting'),
+              description: t(
+                'Apply conditional color formatting to numeric columns',
+              ),
+              metricOnly: true,
+              shouldMapStateToProps() {
+                return true;
+              },
+              mapStateToProps(explore, _, chart) {
+                const chartStatus = chart?.chartStatus;
+                const datasource = explore?.datasource;
+                const verboseMap =
+                  datasource &&
+                  Object.prototype.hasOwnProperty.call(
+                    datasource,
+                    'verbose_map',
+                  )
+                    ? ((datasource as Dataset).verbose_map ?? {})
+                    : {};
+                const columnOptions = [
+                  {
+                    value: 'metric',
+                    label: 'metric',
+                    dataType: GenericDataType.Numeric,
+                  },
+                ];
+                return {
+                  removeIrrelevantConditions: chartStatus === 'success',
+                  columnOptions,
+                  verboseMap,
+                };
+              },
+            },
+          },
+        ],
       ],
     },
   ],
diff --git a/superset-frontend/plugins/plugin-chart-country-map/src/transformProps.ts b/superset-frontend/plugins/plugin-chart-country-map/src/transformProps.ts
index 8267765eb27..fc05a829a7b 100644
--- a/superset-frontend/plugins/plugin-chart-country-map/src/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-country-map/src/transformProps.ts
@@ -22,6 +22,7 @@ import {
   getMetricLabel,
   getValueFormatter,
 } from '@superset-ui/core';
+import { getColorFormatters } from '@superset-ui/chart-controls';
 
 export default function transformProps(chartProps: ChartProps) {
   const {
@@ -33,6 +34,7 @@ export default function transformProps(chartProps: ChartProps) {
     hooks = {},
     filterState,
     emitCrossFilters,
+    theme,
   } = chartProps;
   const {
     entity,
@@ -43,6 +45,7 @@ export default function transformProps(chartProps: ChartProps) {
     colorScheme,
     sliceId,
     metric,
+    conditionalFormatting,
   } = formData;
 
   const {
@@ -64,6 +67,7 @@ export default function transformProps(chartProps: ChartProps) {
       ? { country_id: row[entityLabel], metric: row[metricLabel] }
       : row,
   );
+  const formatters = getColorFormatters(conditionalFormatting, data, theme);
 
   const formatter = getValueFormatter(
     metric,
@@ -94,5 +98,6 @@ export default function transformProps(chartProps: ChartProps) {
     setDataMask,
     emitCrossFilters,
     filterState,
+    formatters,
   };
 }
diff --git a/superset-frontend/plugins/plugin-chart-country-map/test/CountryMap.test.tsx b/superset-frontend/plugins/plugin-chart-country-map/test/CountryMap.test.tsx
index c6d9b1ce501..fcc345f0cef 100644
--- a/superset-frontend/plugins/plugin-chart-country-map/test/CountryMap.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-country-map/test/CountryMap.test.tsx
@@ -20,6 +20,8 @@
 import '@testing-library/jest-dom';
 import { render, fireEvent } from '@testing-library/react';
 import d3 from 'd3';
+import { extent as d3Extent } from 'd3-array';
+import { getSequentialSchemeRegistry } from '@superset-ui/core';
 import ReactCountryMap from '../src/ReactCountryMap';
 
 // d3 v3 APIs have loose types; cast to allow jest mock operations
@@ -74,6 +76,40 @@ const mockMapData = {
 
 type D3JsonCallback = (error: Error | null, data: unknown) => void;
 
+type CountryMapDatum = {
+  country_id: string;
+  metric: number;
+};
+
+function expectedLinearFill(
+  data: CountryMapDatum[],
+  linearColorScheme: string,
+): string {
+  const rawExtents = d3Extent(data, v => v.metric);
+  const extents: [number, number] =
+    rawExtents[0] != null && rawExtents[1] != null
+      ? [rawExtents[0], rawExtents[1]]
+      : [0, 1];
+  const colorSchemeObj = getSequentialSchemeRegistry().get(linearColorScheme);
+  const linearColorScale = colorSchemeObj
+    ? colorSchemeObj.createLinearScale(extents)
+    : () => '#ccc';
+  return linearColorScale(data[0].metric) ?? '#ccc';
+}
+
+function expectFillToMatchLinearScheme(
+  region: Element | null,
+  data: CountryMapDatum[],
+  linearColorScheme: string,
+): void {
+  expect(region).not.toBeNull();
+  const { fill } = (region as HTMLElement).style;
+  expect(fill).toBeTruthy();
+  expect(d3Any.rgb(fill).toString()).toBe(
+    d3Any.rgb(expectedLinearFill(data, linearColorScheme)).toString(),
+  );
+}
+
 describe('CountryMap (legacy d3)', () => {
   beforeEach(() => {
     jest.clearAllMocks();
@@ -246,3 +282,135 @@ describe('CountryMap (legacy d3)', () => {
     });
   });
 });
+
+describe('CountryMap conditional formatting', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  test('applies conditional formatting color when formatter matches metric value', async () => {
+    d3Any.json.mockImplementation((_url: string, cb: D3JsonCallback) =>
+      cb(null, mockMapData),
+    );
+
+    const mockFormatters = [
+      {
+        column: 'metric',
+        getColorFromValue: (val: number) =>
+          val >= 100 ? '#FF0000' : undefined,
+      },
+    ];
+
+    render(
+      <ReactCountryMap
+        width={500}
+        height={300}
+        data={[{ country_id: 'CAN', metric: 100 }]}
+        country="canada"
+        linearColorScheme="bnbColors"
+        colorScheme=""
+        formatter={jest.fn().mockReturnValue('100')}
+        formatters={mockFormatters}
+      />,
+    );
+
+    const region = document.querySelector('path.region');
+    expect(region).not.toBeNull();
+    expect(region).toHaveStyle({ fill: '#FF0000' });
+  });
+
+  test('falls back to default color when conditional formatter threshold is not met', async () => {
+    d3Any.json.mockImplementation((_url: string, cb: D3JsonCallback) =>
+      cb(null, mockMapData),
+    );
+
+    const mockFormatters = [
+      {
+        column: 'metric',
+        getColorFromValue: (val: number) => (val > 500 ? '#FF0000' : undefined),
+      },
+    ];
+
+    render(
+      <ReactCountryMap
+        width={500}
+        height={300}
+        data={[{ country_id: 'CAN', metric: 100 }]}
+        country="canada"
+        linearColorScheme="bnbColors"
+        colorScheme=""
+        formatter={jest.fn().mockReturnValue('100')}
+        formatters={mockFormatters}
+      />,
+    );
+
+    const region = document.querySelector('path.region');
+    expect(region).not.toHaveStyle({ fill: '#FF0000' });
+    expectFillToMatchLinearScheme(
+      region,
+      [{ country_id: 'CAN', metric: 100 }],
+      'bnbColors',
+    );
+  });
+
+  test('evaluates multiple formatters in order and applies the first match', async () => {
+    d3Any.json.mockImplementation((_url: string, cb: D3JsonCallback) =>
+      cb(null, mockMapData),
+    );
+
+    const mockFormatters = [
+      {
+        column: 'metric',
+        getColorFromValue: (val: number) => (val > 200 ? '#FF0000' : undefined),
+      },
+      {
+        column: 'metric',
+        getColorFromValue: (val: number) =>
+          val >= 100 ? '#00FF00' : undefined,
+      },
+    ];
+
+    render(
+      <ReactCountryMap
+        width={500}
+        height={300}
+        data={[{ country_id: 'CAN', metric: 100 }]}
+        country="canada"
+        linearColorScheme="bnbColors"
+        colorScheme=""
+        formatter={jest.fn().mockReturnValue('100')}
+        formatters={mockFormatters}
+      />,
+    );
+
+    const region = document.querySelector('path.region');
+    expect(region).not.toBeNull();
+    expect(region).toHaveStyle({ fill: '#00FF00' });
+  });
+
+  test('handles empty or undefined formatters gracefully without crashing', async () => {
+    d3Any.json.mockImplementation((_url: string, cb: D3JsonCallback) =>
+      cb(null, mockMapData),
+    );
+
+    render(
+      <ReactCountryMap
+        width={500}
+        height={300}
+        data={[{ country_id: 'CAN', metric: 100 }]}
+        country="canada"
+        linearColorScheme="bnbColors"
+        colorScheme=""
+        formatter={jest.fn().mockReturnValue('100')}
+        formatters={undefined}
+      />,
+    );
+
+    const region = document.querySelector('path.region');
+    expectFillToMatchLinearScheme(
+      region,
+      [{ country_id: 'CAN', metric: 100 }],
+      'bnbColors',
+    );
+  });
+});
diff --git a/superset-frontend/plugins/plugin-chart-country-map/test/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-country-map/test/transformProps.test.ts
index 18fd8426736..6b25e9eef51 100644
--- a/superset-frontend/plugins/plugin-chart-country-map/test/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-country-map/test/transformProps.test.ts
@@ -17,6 +17,7 @@
  * under the License.
  */
 import { ChartProps } from '@superset-ui/core';
+import { Comparator } from '@superset-ui/chart-controls';
 import transformProps from '../src/transformProps';
 
 const onContextMenu = jest.fn();
@@ -127,3 +128,29 @@ test('renames v1 API records using adhoc metric labels', () => {
   );
   expect(transformed.data).toEqual([{ country_id: 'FRA', metric: 3.14 }]);
 });
+
+test('builds color formatters from conditional formatting config', () => {
+  const transformed = transformProps(
+    createProps({
+      conditionalFormatting: [
+        {
+          column: 'metric',
+          colorScheme: '#FF0000',
+          operator: Comparator.GreaterThan,
+          targetValue: 50,
+          useGradient: false,
+        },
+      ],
+    }),
+  );
+
+  expect(transformed.formatters).toHaveLength(1);
+  expect(transformed.formatters?.[0].column).toBe('metric');
+  expect(transformed.formatters?.[0].getColorFromValue(100)).toBe('#FF0000');
+  expect(transformed.formatters?.[0].getColorFromValue(10)).toBeUndefined();
+});
+
+test('returns an empty formatters array when conditional formatting is unset', () => {
+  const transformed = transformProps(createProps());
+  expect(transformed.formatters).toEqual([]);
+});
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
index 1f63481c21b..aed76ed494a 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
@@ -75,6 +75,7 @@ const ConditionalFormattingControl = ({
   removeIrrelevantConditions,
   extraColorChoices,
   allColumns,
+  metricOnly,
   serverPagination,
   ...props
 }: ConditionalFormattingControlProps) => {
@@ -166,6 +167,7 @@ const ConditionalFormattingControl = ({
               destroyOnHidden
               extraColorChoices={extraColorChoices}
               allColumns={allColumns}
+              metricOnly={metricOnly}
               serverPagination={serverPagination}
             >
               <OptionControlContainer withCaret>
@@ -184,6 +186,7 @@ const ConditionalFormattingControl = ({
           destroyOnHidden
           extraColorChoices={extraColorChoices}
           allColumns={allColumns}
+          metricOnly={metricOnly}
           serverPagination={serverPagination}
         >
           <AddControlLabel>
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
index 84d766298bc..b0daeb760b5 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
@@ -29,6 +29,7 @@ export const FormattingPopover = ({
   children,
   extraColorChoices,
   allColumns,
+  metricOnly,
   serverPagination,
   ...props
 }: FormattingPopoverProps) => {
@@ -52,6 +53,7 @@ export const FormattingPopover = ({
           columns={columns}
           extraColorChoices={extraColorChoices}
           allColumns={allColumns}
+          metricOnly={metricOnly}
           serverPagination={serverPagination}
         />
       }
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx
index b9552fd59d8..7d61ee7778c 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx
@@ -24,8 +24,12 @@ import {
   userEvent,
   within,
 } from 'spec/helpers/testing-library';
+import {
+  Comparator,
+  ColorSchemeEnum,
+  ObjectFormattingEnum,
+} from '@superset-ui/chart-controls';
 import tinycolor from 'tinycolor2';
-import { Comparator, ColorSchemeEnum } from '@superset-ui/chart-controls';
 import { GenericDataType } from '@apache-superset/core/common';
 import { FormattingPopoverContent } from './FormattingPopoverContent';
 
@@ -430,6 +434,80 @@ test('should not display tooltip icon when extraColorChoices is empty', () => {
   expect(tooltipIcon).not.toBeInTheDocument();
 });
 
+test('hides formatting column and formatting object when metricOnly is true', () => {
+  const mockColumns = [
+    { label: 'Sales', value: 'sales', dataType: GenericDataType.Numeric },
+  ];
+
+  render(
+    <FormattingPopoverContent
+      onChange={mockOnChange}
+      columns={mockColumns}
+      allColumns={mockColumns}
+      metricOnly
+    />,
+  );
+
+  expect(screen.getByLabelText('Column')).toBeInTheDocument();
+  expect(screen.getByLabelText('Color scheme')).toBeInTheDocument();
+  expect(screen.getByLabelText('Operator')).toBeInTheDocument();
+  expect(screen.queryByText('Use gradient')).toBeInTheDocument();
+  expect(screen.queryByText('Formatting column')).not.toBeInTheDocument();
+  expect(screen.queryByText('Formatting object')).not.toBeInTheDocument();
+});
+
+test('shows formatting column and formatting object when metricOnly is false', () => {
+  const mockColumns = [
+    { label: 'Sales', value: 'sales', dataType: GenericDataType.Numeric },
+  ];
+
+  render(
+    <FormattingPopoverContent
+      onChange={mockOnChange}
+      columns={mockColumns}
+      allColumns={mockColumns}
+      metricOnly={false}
+    />,
+  );
+
+  expect(screen.getByLabelText('Column')).toBeInTheDocument();
+  expect(screen.getByLabelText('Color scheme')).toBeInTheDocument();
+  expect(screen.getByLabelText('Operator')).toBeInTheDocument();
+  expect(screen.queryByText('Use gradient')).toBeInTheDocument();
+  expect(screen.queryByText('Formatting column')).toBeInTheDocument();
+  expect(screen.queryByText('Formatting object')).toBeInTheDocument();
+});
+
+test('omits stale formatting targets on submit when metricOnly is true', async () => {
+  mockOnChange.mockClear();
+  const mockColumns = [
+    { label: 'Sales', value: 'sales', dataType: GenericDataType.Numeric },
+  ];
+
+  render(
+    <FormattingPopoverContent
+      onChange={mockOnChange}
+      columns={mockColumns}
+      allColumns={mockColumns}
+      metricOnly
+      config={{
+        column: 'sales',
+        columnFormatting: 'stale_column',
+        objectFormatting: ObjectFormattingEnum.BACKGROUND_COLOR,
+      }}
+    />,
+  );
+
+  fireEvent.click(screen.getByText('Apply'));
+
+  await waitFor(() => {
+    expect(mockOnChange).toHaveBeenCalled();
+  });
+
+  const submitted = mockOnChange.mock.calls[0][0];
+  expect(submitted).not.toHaveProperty('columnFormatting');
+  expect(submitted).not.toHaveProperty('objectFormatting');
+});
 test('shows min/max bound fields for the default None operator on a numeric column', () => {
   render(
     <FormattingPopoverContent
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
index 912148c8525..3e22fecea07 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
@@ -506,12 +506,22 @@ const renderOperatorFields = (
   );
 };
 
+const omitFormattingTargets = (
+  values: ConditionalFormattingConfig,
+): ConditionalFormattingConfig => {
+  const rest: ConditionalFormattingConfig = { ...values };
+  delete rest.columnFormatting;
+  delete rest.objectFormatting;
+  return rest;
+};
+
 export const FormattingPopoverContent = ({
   config,
   onChange,
   columns = [],
   extraColorChoices = [],
   allColumns = [],
+  metricOnly = false,
   serverPagination = false,
 }: {
   config?: ConditionalFormattingConfig;
@@ -519,6 +529,11 @@ export const FormattingPopoverContent = ({
   columns: { label: string; value: string; dataType: GenericDataType }[];
   extraColorChoices?: { label: string; colors: string[] }[];
   allColumns?: ColumnOption[];
+  /**
+   * Hide formatting-target fields (columnFormatting / objectFormatting)
+   * so the control applies only to the selected metric.
+   */
+  metricOnly?: boolean;
   serverPagination?: boolean;
 }) => {
   const [form] = Form.useForm();
@@ -543,8 +558,22 @@ export const FormattingPopoverContent = ({
     config?.column || columns[0]?.value,
   );
   const visibleAllColumns = useMemo(
-    () => !!(allColumns && Array.isArray(allColumns) && allColumns.length),
-    [allColumns],
+    () =>
+      !metricOnly &&
+      !!(allColumns && Array.isArray(allColumns) && allColumns.length),
+    [allColumns, metricOnly],
+  );
+
+  const formInitialValues = useMemo(
+    () => (metricOnly && config ? omitFormattingTargets(config) : config),
+    [config, metricOnly],
+  );
+
+  const handleFinish = useCallback(
+    (values: ConditionalFormattingConfig) => {
+      onChange(metricOnly ? omitFormattingTargets(values) : values);
+    },
+    [metricOnly, onChange],
   );
 
   const [columnFormatting, setColumnFormatting] = useState<string | undefined>(
@@ -601,8 +630,8 @@ export const FormattingPopoverContent = ({
     () => allColumns.filter(col => col.dataType === GenericDataType.Numeric),
     [allColumns],
   );
-  const defaultColorToken = colors[0]?.colors?.[0];
 
+  const defaultColorToken = colors[0]?.colors?.[0];
   const visibleUseGradient = useMemo(
     () =>
       numericColumns.length > 0
@@ -659,8 +688,8 @@ export const FormattingPopoverContent = ({
   return (
     <Form
       form={form}
-      onFinish={onChange}
-      initialValues={config}
+      onFinish={handleFinish}
+      initialValues={formInitialValues}
       requiredMark="optional"
       layout="vertical"
     >
@@ -742,7 +771,7 @@ export const FormattingPopoverContent = ({
           </Col>
         </Row>
       ) : null}
-      {visibleUseGradient && (
+      {(metricOnly || visibleUseGradient) && (
         <Row gutter={20}>
           <Col span={1}>
             <FormItem
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
index 791e669b735..6d836a53ab8 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
@@ -61,6 +61,11 @@ export type ConditionalFormattingControlProps = ControlComponentProps<
   description: string;
   extraColorChoices?: { label: string; colors: string[] }[];
   allColumns?: ColumnOption[];
+  /**
+   * Hide formatting-target fields (columnFormatting / objectFormatting)
+   * so the control applies only to the selected metric.
+   */
+  metricOnly?: boolean;
   serverPagination?: boolean;
 };
 
@@ -72,6 +77,11 @@ export type FormattingPopoverProps = PopoverProps & {
   children: ReactNode;
   extraColorChoices?: { label: string; colors: string[] }[];
   allColumns?: ColumnOption[];
+  /**
+   * Hide formatting-target fields (columnFormatting / objectFormatting)
+   * so the control applies only to the selected metric.
+   */
+  metricOnly?: boolean;
   serverPagination?: boolean;
 };