You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2025/10/28 23:40:47 UTC

(superset) branch master updated: feat: conditional formatting improvements add flag toAllRow and toTextColor in tables (#34762)

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

rusackas 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 514d56d1ae feat: conditional formatting improvements add flag toAllRow and  toTextColor in tables (#34762)
514d56d1ae is described below

commit 514d56d1aeb16e498163198808167363ec5f9649
Author: SBIN2010 <Sb...@mail.ru>
AuthorDate: Wed Oct 29 02:40:40 2025 +0300

    feat: conditional formatting improvements add flag toAllRow and  toTextColor in tables (#34762)
---
 .../superset-ui-chart-controls/src/types.ts        |   4 +
 .../src/utils/getColorFormatters.ts                |   2 +
 .../plugins/plugin-chart-table/src/TableChart.tsx  |  40 +++++---
 .../plugin-chart-table/src/controlPanel.tsx        |  25 +++++
 .../plugin-chart-table/test/TableChart.test.tsx    | 106 +++++++++++++++++++++
 .../ConditionalFormattingControl.tsx               |   2 +
 .../FormattingPopover.tsx                          |   2 +
 .../FormattingPopoverContent.test.tsx              |  41 ++++++++
 .../FormattingPopoverContent.tsx                   |  85 ++++++++++++++++-
 .../controls/ConditionalFormattingControl/types.ts |   9 ++
 10 files changed, 301 insertions(+), 15 deletions(-)

diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
index ed83551df2..ba3c957d68 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
@@ -478,10 +478,14 @@ export type ConditionalFormattingConfig = {
   targetValueRight?: number;
   column?: string;
   colorScheme?: string;
+  toAllRow?: boolean;
+  toTextColor?: boolean;
 };
 
 export type ColorFormatters = {
   column: string;
+  toAllRow?: boolean;
+  toTextColor?: boolean;
   getColorFromValue: (value: number | string) => string | undefined;
 }[];
 
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/getColorFormatters.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/getColorFormatters.ts
index 249037a4cf..f6b341bb64 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/utils/getColorFormatters.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/getColorFormatters.ts
@@ -267,6 +267,8 @@ export const getColorFormatters = memoizeOne(
         ) {
           acc.push({
             column: config?.column,
+            toAllRow: config?.toAllRow,
+            toTextColor: config?.toTextColor,
             getColorFromValue: getColorFunction(
               { ...config, colorScheme: resolvedColorScheme },
               data.map(row => row[config.column!] as number),
diff --git a/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx b/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
index 578ea00a0e..d021eedfb6 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/src/TableChart.tsx
@@ -70,6 +70,7 @@ import {
   TableOutlined,
 } from '@ant-design/icons';
 import { isEmpty, debounce, isEqual } from 'lodash';
+import { ColorFormatters } from '@superset-ui/chart-controls';
 import {
   ColorSchemeEnum,
   DataColumnMeta,
@@ -855,6 +856,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
           const html = isHtml && allowRenderHtml ? { __html: text } : undefined;
 
           let backgroundColor;
+          let color;
           let arrow = '';
           const originKey = column.key.substring(column.label.length).trim();
           if (!hasColumnColorFormatters && hasBasicColorFormatters) {
@@ -867,17 +869,33 @@ export default function TableChart<D extends DataRecord = DataRecord>(
           }
 
           if (hasColumnColorFormatters) {
-            columnColorFormatters!
+            const applyFormatter = (
+              formatter: ColorFormatters[number],
+              valueToFormat: any,
+            ) => {
+              const hasValue =
+                valueToFormat !== undefined && valueToFormat !== null;
+              if (!hasValue) return;
+
+              const formatterResult =
+                formatter.getColorFromValue(valueToFormat);
+              if (!formatterResult) return;
+
+              if (formatter.toTextColor) {
+                color = formatterResult.slice(0, -2);
+              } else {
+                backgroundColor = formatterResult;
+              }
+            };
+            columnColorFormatters
               .filter(formatter => formatter.column === column.key)
-              .forEach(formatter => {
-                const formatterResult =
-                  value || value === 0
-                    ? formatter.getColorFromValue(value as number)
-                    : false;
-                if (formatterResult) {
-                  backgroundColor = formatterResult;
-                }
-              });
+              .forEach(formatter => applyFormatter(formatter, value));
+
+            columnColorFormatters
+              .filter(formatter => formatter.toAllRow)
+              .forEach(formatter =>
+                applyFormatter(formatter, row.original[formatter.column]),
+              );
           }
 
           if (
@@ -893,7 +911,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
                 : '';
           }
           const StyledCell = styled.td`
-            color: ${theme.colorText};
+            color: ${color ? `${color}FF` : theme.colorText};
             text-align: ${sharedStyle.textAlign};
             white-space: ${value instanceof Date ? 'nowrap' : undefined};
             position: relative;
diff --git a/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
index 35d3de8d7e..859c74bf4c 100644
--- a/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
@@ -39,6 +39,7 @@ import {
   shouldSkipMetricColumn,
   isRegularMetric,
   isPercentMetric,
+  ConditionalFormattingConfig,
 } from '@superset-ui/chart-controls';
 import {
   ensureIsArray,
@@ -767,6 +768,26 @@ const config: ControlPanelConfig = {
                   ? (explore?.datasource as Dataset)?.verbose_map
                   : (explore?.datasource?.columns ?? {});
                 const chartStatus = chart?.chartStatus;
+                const value = _?.value ?? [];
+                if (value && Array.isArray(value)) {
+                  value.forEach(
+                    (item: ConditionalFormattingConfig, index, array) => {
+                      if (
+                        item.colorScheme &&
+                        !['Green', 'Red'].includes(item.colorScheme)
+                      ) {
+                        if (!item.toAllRow || !item.toTextColor) {
+                          // eslint-disable-next-line no-param-reassign
+                          array[index] = {
+                            ...item,
+                            toAllRow: item.toAllRow ?? false,
+                            toTextColor: item.toTextColor ?? false,
+                          };
+                        }
+                      }
+                    },
+                  );
+                }
                 const { colnames, coltypes } =
                   chart?.queriesResponse?.[0] ?? {};
                 const numericColumns =
@@ -801,6 +822,10 @@ const config: ControlPanelConfig = {
                   removeIrrelevantConditions: chartStatus === 'success',
                   columnOptions,
                   verboseMap,
+                  conditionalFormattingFlag: {
+                    toAllRowCheck: true,
+                    toColorTextCheck: true,
+                  },
                 };
               },
             },
diff --git a/superset-frontend/plugins/plugin-chart-table/test/TableChart.test.tsx b/superset-frontend/plugins/plugin-chart-table/test/TableChart.test.tsx
index e7feffd9d1..9f2c1a9d23 100644
--- a/superset-frontend/plugins/plugin-chart-table/test/TableChart.test.tsx
+++ b/superset-frontend/plugins/plugin-chart-table/test/TableChart.test.tsx
@@ -756,6 +756,112 @@ describe('plugin-chart-table', () => {
           'rgba(172, 225, 196, 1)',
         );
       });
+
+      it('render color with column color formatter to entire row', () => {
+        render(
+          ProviderWrapper({
+            children: (
+              <TableChart
+                {...transformProps({
+                  ...testData.advanced,
+                  rawFormData: {
+                    ...testData.advanced.rawFormData,
+                    conditional_formatting: [
+                      {
+                        colorScheme: '#ACE1C4',
+                        column: 'sum__num',
+                        operator: '>',
+                        targetValue: 2467,
+                        toAllRow: true,
+                      },
+                    ],
+                  },
+                })}
+              />
+            ),
+          }),
+        );
+
+        expect(getComputedStyle(screen.getByText('Michael')).background).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+        expect(getComputedStyle(screen.getByTitle('2467063')).background).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+        expect(getComputedStyle(screen.getByTitle('0.123456')).background).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+      });
+
+      it('display text color using column color formatter', () => {
+        render(
+          ProviderWrapper({
+            children: (
+              <TableChart
+                {...transformProps({
+                  ...testData.advanced,
+                  rawFormData: {
+                    ...testData.advanced.rawFormData,
+                    conditional_formatting: [
+                      {
+                        colorScheme: '#ACE1C4',
+                        column: 'sum__num',
+                        operator: '>',
+                        targetValue: 2467,
+                        toTextColor: true,
+                      },
+                    ],
+                  },
+                })}
+              />
+            ),
+          }),
+        );
+
+        expect(getComputedStyle(screen.getByTitle('2467063')).color).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+        expect(getComputedStyle(screen.getByTitle('2467')).color).toBe(
+          'rgba(0, 0, 0, 0.88)',
+        );
+      });
+
+      it('display text color using column color formatter for entire row', () => {
+        render(
+          ProviderWrapper({
+            children: (
+              <TableChart
+                {...transformProps({
+                  ...testData.advanced,
+                  rawFormData: {
+                    ...testData.advanced.rawFormData,
+                    conditional_formatting: [
+                      {
+                        colorScheme: '#ACE1C4',
+                        column: 'sum__num',
+                        operator: '>',
+                        targetValue: 2467,
+                        toAllRow: true,
+                        toTextColor: true,
+                      },
+                    ],
+                  },
+                })}
+              />
+            ),
+          }),
+        );
+
+        expect(getComputedStyle(screen.getByText('Michael')).color).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+        expect(getComputedStyle(screen.getByTitle('2467063')).color).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+        expect(getComputedStyle(screen.getByTitle('0.123456')).color).toBe(
+          'rgba(172, 225, 196, 1)',
+        );
+      });
     });
   });
 });
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
index 25e38d5f97..a9c0fe15f6 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/ConditionalFormattingControl.tsx
@@ -73,6 +73,7 @@ const ConditionalFormattingControl = ({
   verboseMap,
   removeIrrelevantConditions,
   extraColorChoices,
+  conditionalFormattingFlag,
   ...props
 }: ConditionalFormattingControlProps) => {
   const [conditionalFormattingConfigs, setConditionalFormattingConfigs] =
@@ -173,6 +174,7 @@ const ConditionalFormattingControl = ({
           onChange={onSave}
           destroyTooltipOnHide
           extraColorChoices={extraColorChoices}
+          conditionalFormattingFlag={conditionalFormattingFlag}
         >
           <AddControlLabel>
             <Icons.PlusOutlined
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
index dd6aef1f0a..021fc5f8bc 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopover.tsx
@@ -28,6 +28,7 @@ export const FormattingPopover = ({
   config,
   children,
   extraColorChoices,
+  conditionalFormattingFlag,
   ...props
 }: FormattingPopoverProps) => {
   const [visible, setVisible] = useState(false);
@@ -49,6 +50,7 @@ export const FormattingPopover = ({
           config={config}
           columns={columns}
           extraColorChoices={extraColorChoices}
+          conditionalFormattingFlag={conditionalFormattingFlag}
         />
       }
       open={visible}
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 74c5b33395..aaa17cd67d 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.test.tsx
@@ -26,6 +26,7 @@ import { Comparator } from '@superset-ui/chart-controls';
 import { ColorSchemeEnum } from '@superset-ui/plugin-chart-table';
 import { GenericDataType } from '@apache-superset/core/api/core';
 import { FormattingPopoverContent } from './FormattingPopoverContent';
+import { ConditionalFormattingConfig } from './types';
 
 const mockOnChange = jest.fn();
 
@@ -50,6 +51,11 @@ const extraColorChoices = [
   },
 ];
 
+const config: ConditionalFormattingConfig = {
+  toAllRow: true,
+  toTextColor: true,
+};
+
 test('renders FormattingPopoverContent component', () => {
   render(
     <FormattingPopoverContent
@@ -141,3 +147,38 @@ test('displays the correct input fields based on the selected string type operat
   fireEvent.click(await screen.findByTitle('begins with'));
   expect(await screen.findByLabelText('Target value')).toBeInTheDocument();
 });
+
+test('displays the toAllRow and toTextColor flags based on the selected numeric type operator', () => {
+  render(
+    <FormattingPopoverContent
+      onChange={mockOnChange}
+      columns={columns}
+      config={config}
+    />,
+  );
+
+  expect(screen.getByText('To entire row')).toBeInTheDocument();
+  expect(screen.getByText('To text color')).toBeInTheDocument();
+});
+
+test('displays the toAllRow and toTextColor flags based on the selected string type operator', () => {
+  render(
+    <FormattingPopoverContent
+      onChange={mockOnChange}
+      columns={columnsStringType}
+      config={config}
+    />,
+  );
+
+  expect(screen.getByText('To entire row')).toBeInTheDocument();
+  expect(screen.getByText('To text color')).toBeInTheDocument();
+});
+
+test('Not displays the toAllRow and toTextColor flags', () => {
+  render(
+    <FormattingPopoverContent onChange={mockOnChange} columns={columns} />,
+  );
+
+  expect(screen.queryByText('To entire row')).not.toBeInTheDocument();
+  expect(screen.queryByText('To text color')).not.toBeInTheDocument();
+});
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
index 2c75f249ed..8090509250 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/FormattingPopoverContent.tsx
@@ -32,9 +32,13 @@ import {
   Input,
   Col,
   Row,
+  Checkbox,
   type FormProps,
 } from '@superset-ui/core/components';
-import { ConditionalFormattingConfig } from './types';
+import {
+  ConditionalFormattingConfig,
+  ConditionalFormattingFlag,
+} from './types';
 
 // TODO: tangled redefinition that aligns with @superset-ui/plugin-chart-table
 // used to be imported but main app shouldn't depend on plugins...
@@ -58,9 +62,9 @@ const JustifyEnd = styled.div`
 
 // Use theme token names instead of hex values to support theme switching
 const colorSchemeOptions = () => [
-  { value: 'colorSuccessBg', label: t('success') },
-  { value: 'colorWarningBg', label: t('alert') },
-  { value: 'colorErrorBg', label: t('error') },
+  { value: 'colorSuccess', label: t('success') },
+  { value: 'colorWarning', label: t('alert') },
+  { value: 'colorError', label: t('error') },
 ];
 
 const operatorOptions = [
@@ -233,11 +237,16 @@ export const FormattingPopoverContent = ({
   onChange,
   columns = [],
   extraColorChoices = [],
+  conditionalFormattingFlag = {
+    toAllRowCheck: false,
+    toColorTextCheck: false,
+  },
 }: {
   config?: ConditionalFormattingConfig;
   onChange: (config: ConditionalFormattingConfig) => void;
   columns: { label: string; value: string; dataType: GenericDataType }[];
   extraColorChoices?: { label: string; value: string }[];
+  conditionalFormattingFlag?: ConditionalFormattingFlag;
 }) => {
   const [form] = Form.useForm();
   const colorScheme = colorSchemeOptions();
@@ -246,6 +255,33 @@ export const FormattingPopoverContent = ({
       (config?.colorScheme !== ColorSchemeEnum.Green &&
         config?.colorScheme !== ColorSchemeEnum.Red),
   );
+
+  const [toAllRow, setToAllRow] = useState(() => Boolean(config?.toAllRow));
+  const [toTextColor, setToTextColor] = useState(() =>
+    Boolean(config?.toTextColor),
+  );
+
+  const useConditionalFormattingFlag = (
+    flagKey: 'toAllRowCheck' | 'toColorTextCheck',
+    configKey: 'toAllRow' | 'toTextColor',
+  ) =>
+    useMemo(
+      () =>
+        conditionalFormattingFlag && conditionalFormattingFlag[flagKey]
+          ? config?.[configKey] === undefined
+          : config?.[configKey] !== undefined,
+      [conditionalFormattingFlag, config],
+    );
+
+  const showToAllRow = useConditionalFormattingFlag(
+    'toAllRowCheck',
+    'toAllRow',
+  );
+  const showToColorText = useConditionalFormattingFlag(
+    'toColorTextCheck',
+    'toTextColor',
+  );
+
   const handleChange = (event: any) => {
     setShowOperatorFields(
       !(event === ColorSchemeEnum.Green || event === ColorSchemeEnum.Red),
@@ -339,6 +375,47 @@ export const FormattingPopoverContent = ({
           </Row>
         )}
       </FormItem>
+      <Row>
+        {showOperatorFields && showToAllRow && (
+          <Row gutter={20}>
+            <Col span={1}>
+              <FormItem
+                name="toAllRow"
+                valuePropName="checked"
+                initialValue={toAllRow}
+              >
+                <Checkbox
+                  onChange={event => setToAllRow(event.target.checked)}
+                  checked={toAllRow}
+                />
+              </FormItem>
+            </Col>
+            <Col>
+              <FormItem required>{t('To entire row')}</FormItem>
+            </Col>
+          </Row>
+        )}
+        {showOperatorFields && showToColorText && (
+          <Row gutter={20}>
+            <Col span={1}>
+              <FormItem
+                name="toTextColor"
+                valuePropName="checked"
+                initialValue={toTextColor}
+              >
+                <Checkbox
+                  onChange={event => setToTextColor(event.target.checked)}
+                  checked={toTextColor}
+                />
+              </FormItem>
+            </Col>
+            <Col>
+              <FormItem required>{t('To text color')}</FormItem>
+            </Col>
+          </Row>
+        )}
+      </Row>
+
       <FormItem>
         <JustifyEnd>
           <Button htmlType="submit" buttonStyle="primary">
diff --git a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
index bbd37803e2..242925dce9 100644
--- a/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
+++ b/superset-frontend/src/explore/components/controls/ConditionalFormattingControl/types.ts
@@ -29,6 +29,8 @@ export type ConditionalFormattingConfig = {
   targetValueRight?: number;
   column?: string;
   colorScheme?: string;
+  toAllRow?: boolean;
+  toTextColor?: boolean;
 };
 
 export type ConditionalFormattingControlProps = ControlComponentProps<
@@ -40,6 +42,7 @@ export type ConditionalFormattingControlProps = ControlComponentProps<
   label: string;
   description: string;
   extraColorChoices?: { label: string; value: string }[];
+  conditionalFormattingFlag?: ConditionalFormattingFlag;
 };
 
 export type FormattingPopoverProps = PopoverProps & {
@@ -49,4 +52,10 @@ export type FormattingPopoverProps = PopoverProps & {
   title: string;
   children: ReactNode;
   extraColorChoices?: { label: string; value: string }[];
+  conditionalFormattingFlag?: ConditionalFormattingFlag;
+};
+
+export type ConditionalFormattingFlag = {
+  toAllRowCheck?: boolean;
+  toColorTextCheck?: boolean;
 };