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 2026/08/08 07:27:19 UTC
(superset) branch feat/color-picker-consolidation created (now 7546cfe744b)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a change to branch feat/color-picker-consolidation
in repository https://gitbox.apache.org/repos/asf/superset.git
at 7546cfe744b feat(themes): add curated color pickers above the theme JSON editor
This branch includes the following new commits:
new 063779e9b23 feat(gauge): replace scheme-index interval colors with a color picker
new 9ef9005c84b feat(bullet): add optional per-range band colors
new c410906061d feat(big-number): replace 2-choice comparison scheme with color pickers
new 7546cfe744b feat(themes): add curated color pickers above the theme JSON editor
The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(superset) 04/04: feat(themes): add curated color pickers above the theme JSON editor
Posted by ru...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch feat/color-picker-consolidation
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 7546cfe744b084651bfd04081e104e8279e27314
Author: Claude Code <no...@anthropic.com>
AuthorDate: Fri Aug 7 23:52:03 2026 -0700
feat(themes): add curated color pickers above the theme JSON editor
The admin Theme editor (ThemeModal) only exposed antd theming as a
single JSON textarea, requiring admins to paste in a whole token
object generated by an external tool just to change, say, the brand
color.
Add a "Colors" section (ThemeColorPickers) above the JSON textarea
with one ColorPickerControl per curated antd token: the 5 SEED colors
(colorPrimary, colorSuccess, colorWarning, colorError, colorInfo) plus
6 load-bearing map/alias tokens (colorLink, colorText,
colorTextSecondary, colorBgBase, colorBgContainer, colorBorder). This
intentionally does not attempt to cover the full 100+ token surface --
anything else stays fully editable via the JSON textarea, which
remains the source of truth. Token names are taken directly from
antd's own SeedToken/MapToken types, not invented.
Sync is two-way and implemented as two small, independently tested
pure functions (`tryParseThemeJson`, `patchThemeJsonToken`):
- Picker -> JSON: patches just that one key into the JSON's `token`
object and re-serializes with the same 2-space indent used
elsewhere in this modal, preserving every other key (curated or
not) and their values.
- JSON -> pickers: each render re-parses the JSON textarea's current
value and re-derives picker values from it, so typing in the
textarea updates the matching swatches live.
- Invalid/mid-edit JSON: `tryParseThemeJson` returns null instead of
throwing (matching the file's existing `isValidJson` convention);
the section shows a small notice and pickers stop persisting edits
until the JSON is valid again, rather than crashing or silently
clobbering the textarea.
The section is hidden for read-only system themes, matching the
existing Format/Apply button visibility, and both directions of sync,
invalid-JSON handling, and "uncurated token survives a picker edit"
are covered in ThemeColorPickers.test.tsx (unit) and ThemeModal.test.tsx
(integration).
---
.../src/features/themes/ThemeColorPickers.test.tsx | 192 +++++++++++++++++++++
.../src/features/themes/ThemeColorPickers.tsx | 159 +++++++++++++++++
.../src/features/themes/ThemeModal.test.tsx | 148 ++++++++++++++++
.../src/features/themes/ThemeModal.tsx | 10 ++
4 files changed, 509 insertions(+)
diff --git a/superset-frontend/src/features/themes/ThemeColorPickers.test.tsx b/superset-frontend/src/features/themes/ThemeColorPickers.test.tsx
new file mode 100644
index 00000000000..7277e6ab532
--- /dev/null
+++ b/superset-frontend/src/features/themes/ThemeColorPickers.test.tsx
@@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
+import ThemeColorPickers, {
+ CURATED_COLOR_TOKENS,
+ patchThemeJsonToken,
+ tryParseThemeJson,
+} from './ThemeColorPickers';
+
+test('tryParseThemeJson returns null for empty, blank, or invalid JSON', () => {
+ expect(tryParseThemeJson(undefined)).toBeNull();
+ expect(tryParseThemeJson('')).toBeNull();
+ expect(tryParseThemeJson(' ')).toBeNull();
+ expect(tryParseThemeJson('{ "token": { invalid')).toBeNull();
+ expect(tryParseThemeJson('"just a string"')).toBeNull();
+});
+
+test('tryParseThemeJson returns the parsed object for valid JSON', () => {
+ expect(tryParseThemeJson('{"token":{"colorPrimary":"#1890ff"}}')).toEqual({
+ token: { colorPrimary: '#1890ff' },
+ });
+});
+
+test('patchThemeJsonToken sets the token under an empty theme', () => {
+ const result = patchThemeJsonToken('{}', 'colorPrimary', '#336699');
+ expect(JSON.parse(result)).toEqual({ token: { colorPrimary: '#336699' } });
+});
+
+test('patchThemeJsonToken preserves every other key, curated or not', () => {
+ const original = JSON.stringify({
+ token: {
+ colorPrimary: '#1890ff',
+ colorSuccess: '#52c41a',
+ someUncuratedToken: 'value',
+ },
+ components: { Button: { borderRadius: 4 } },
+ });
+
+ const result = patchThemeJsonToken(original, 'colorPrimary', '#ff0000');
+
+ expect(JSON.parse(result)).toEqual({
+ token: {
+ colorPrimary: '#ff0000',
+ colorSuccess: '#52c41a',
+ someUncuratedToken: 'value',
+ },
+ components: { Button: { borderRadius: 4 } },
+ });
+});
+
+test('patchThemeJsonToken falls back to an empty object when the input JSON is invalid', () => {
+ const result = patchThemeJsonToken(
+ '{ not valid json',
+ 'colorPrimary',
+ '#336699',
+ );
+ expect(JSON.parse(result)).toEqual({ token: { colorPrimary: '#336699' } });
+});
+
+test('curates exactly the documented SEED + alias tokens, no more no less', () => {
+ expect(CURATED_COLOR_TOKENS.map(t => t.key)).toEqual([
+ 'colorPrimary',
+ 'colorSuccess',
+ 'colorWarning',
+ 'colorError',
+ 'colorInfo',
+ 'colorLink',
+ 'colorText',
+ 'colorTextSecondary',
+ 'colorBgBase',
+ 'colorBgContainer',
+ 'colorBorder',
+ ]);
+});
+
+test('renders a picker row for every curated token', () => {
+ render(
+ <ThemeColorPickers
+ jsonData={JSON.stringify({ token: { colorPrimary: '#1890ff' } })}
+ onChange={jest.fn()}
+ />,
+ );
+
+ CURATED_COLOR_TOKENS.forEach(({ key }) => {
+ expect(screen.getByTestId(`theme-color-picker-${key}`)).toBeInTheDocument();
+ });
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ CURATED_COLOR_TOKENS.length,
+ );
+});
+
+test('shows the invalid-JSON notice and does not crash when jsonData is mid-edit', () => {
+ render(
+ <ThemeColorPickers
+ jsonData='{ "token": { "colorPrimary"'
+ onChange={jest.fn()}
+ />,
+ );
+
+ expect(
+ screen.getByTestId('theme-color-pickers-invalid-json-notice'),
+ ).toBeInTheDocument();
+ // still renders every picker row without throwing, just with no value
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ CURATED_COLOR_TOKENS.length,
+ );
+});
+
+test('calls onChange with the patched JSON when a picker value changes', async () => {
+ const onChange = jest.fn();
+ render(
+ <ThemeColorPickers
+ jsonData={JSON.stringify({ token: { colorPrimary: '#1890ff' } }, null, 2)}
+ onChange={onChange}
+ />,
+ );
+
+ const trigger = screen
+ .getByTestId('theme-color-picker-colorSuccess')
+ .querySelector('.ant-color-picker-trigger');
+ expect(trigger).toBeInTheDocument();
+ await userEvent.click(trigger!);
+
+ await waitFor(() => {
+ expect(document.querySelector('.ant-color-picker')).toBeInTheDocument();
+ });
+
+ const hexInput = document.querySelector<HTMLInputElement>(
+ '.ant-color-picker-input input',
+ );
+ expect(hexInput).toBeInTheDocument();
+ await userEvent.clear(hexInput!);
+ await userEvent.type(hexInput!, '00ff00{enter}');
+
+ await waitFor(() => {
+ expect(onChange).toHaveBeenCalled();
+ });
+ const patched = JSON.parse(
+ onChange.mock.calls[onChange.mock.calls.length - 1][0],
+ );
+ expect(patched.token.colorSuccess.toLowerCase()).toBe('#00ff00');
+ // the pre-existing, uncurated-in-this-edit token survives untouched
+ expect(patched.token.colorPrimary).toBe('#1890ff');
+});
+
+test('does not call onChange when disabled', async () => {
+ const onChange = jest.fn();
+ render(
+ <ThemeColorPickers
+ jsonData={JSON.stringify({ token: { colorPrimary: '#1890ff' } })}
+ onChange={onChange}
+ disabled
+ />,
+ );
+
+ const trigger = screen
+ .getByTestId('theme-color-picker-colorPrimary')
+ .querySelector('.ant-color-picker-trigger');
+ await userEvent.click(trigger!);
+
+ await waitFor(() => {
+ expect(document.querySelector('.ant-color-picker')).toBeInTheDocument();
+ });
+ const hexInput = document.querySelector<HTMLInputElement>(
+ '.ant-color-picker-input input',
+ );
+ await userEvent.clear(hexInput!);
+ await userEvent.type(hexInput!, '00ff00{enter}');
+
+ expect(onChange).not.toHaveBeenCalled();
+});
diff --git a/superset-frontend/src/features/themes/ThemeColorPickers.tsx b/superset-frontend/src/features/themes/ThemeColorPickers.tsx
new file mode 100644
index 00000000000..b9ebe454e48
--- /dev/null
+++ b/superset-frontend/src/features/themes/ThemeColorPickers.tsx
@@ -0,0 +1,159 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { styled } from '@apache-superset/core/theme';
+import { Typography } from '@superset-ui/core/components/Typography';
+import ColorPickerControl from 'src/explore/components/controls/ColorPickerControl';
+import type { ColorPickerValue } from 'src/explore/components/controls/ColorPickerControl';
+
+/**
+ * Curated antd theme SEED tokens (plus a handful of the most load-bearing
+ * MapToken/AliasToken derivatives) surfaced as individual color pickers, so
+ * the common case -- "change the brand color" -- doesn't require pasting a
+ * hand-edited JSON blob. This intentionally does not attempt to cover the
+ * full antd token surface (100+ tokens): anything not listed here is still
+ * fully editable via the JSON textarea below, which remains the source of
+ * truth. Names are taken directly from antd's own `SeedToken` /
+ * `MapToken` types -- see `antd/es/theme/interface/{seeds,maps/colors}.d.ts`
+ * -- never invented.
+ */
+export const CURATED_COLOR_TOKENS = [
+ { key: 'colorPrimary', label: () => t('Primary') },
+ { key: 'colorSuccess', label: () => t('Success') },
+ { key: 'colorWarning', label: () => t('Warning') },
+ { key: 'colorError', label: () => t('Error') },
+ { key: 'colorInfo', label: () => t('Info') },
+ { key: 'colorLink', label: () => t('Link') },
+ { key: 'colorText', label: () => t('Text') },
+ { key: 'colorTextSecondary', label: () => t('Secondary text') },
+ { key: 'colorBgBase', label: () => t('Base background') },
+ { key: 'colorBgContainer', label: () => t('Container background') },
+ { key: 'colorBorder', label: () => t('Border') },
+] as const;
+
+export type CuratedColorToken = (typeof CURATED_COLOR_TOKENS)[number]['key'];
+
+interface ParsedThemeJson {
+ token?: Record<string, unknown>;
+ [key: string]: unknown;
+}
+
+/** Attempts to parse `jsonData` as a theme config object; returns `null`
+ * (never throws) when the JSON is empty, mid-edit, or otherwise invalid --
+ * matching the JSON-parse error handling already used elsewhere in
+ * ThemeModal (`formatJsonData`, `isValidJson`). */
+export const tryParseThemeJson = (
+ jsonData: string | undefined,
+): ParsedThemeJson | null => {
+ if (!jsonData?.trim()) return null;
+ try {
+ const parsed = JSON.parse(jsonData);
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch {
+ return null;
+ }
+};
+
+/** Patches a single curated token into `jsonData`'s `token` object,
+ * preserving every other key (including tokens this UI doesn't curate) and
+ * re-serializing with the same 2-space indent used throughout this modal. */
+export const patchThemeJsonToken = (
+ jsonData: string,
+ key: CuratedColorToken,
+ value: string,
+): string => {
+ const parsed = tryParseThemeJson(jsonData) ?? {};
+ const next = {
+ ...parsed,
+ token: {
+ ...parsed.token,
+ [key]: value,
+ },
+ };
+ return JSON.stringify(next, null, 2);
+};
+
+const TokenGrid = styled.div`
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: ${({ theme }) => theme.sizeUnit * 3}px;
+ margin-bottom: ${({ theme }) => theme.sizeUnit * 4}px;
+`;
+
+const TokenRow = styled.div`
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: ${({ theme }) => theme.sizeUnit * 2}px;
+`;
+
+interface ThemeColorPickersProps {
+ jsonData: string;
+ onChange: (nextJsonData: string) => void;
+ disabled?: boolean;
+}
+
+export default function ThemeColorPickers({
+ jsonData,
+ onChange,
+ disabled = false,
+}: ThemeColorPickersProps) {
+ const parsed = useMemo(() => tryParseThemeJson(jsonData), [jsonData]);
+ const isValid = parsed !== null;
+ const tokenValues = parsed?.token ?? {};
+
+ const handleTokenChange =
+ (key: CuratedColorToken) => (color: ColorPickerValue) => {
+ if (typeof color !== 'string' || !isValid || disabled) return;
+ onChange(patchThemeJsonToken(jsonData, key, color));
+ };
+
+ return (
+ <div data-test="theme-color-pickers">
+ {!isValid && (
+ <Typography.Text
+ type="secondary"
+ data-test="theme-color-pickers-invalid-json-notice"
+ >
+ {t(
+ 'Fix the JSON errors below to edit colors here; your changes ' +
+ 'sync automatically once the JSON is valid again.',
+ )}
+ </Typography.Text>
+ )}
+ <TokenGrid>
+ {CURATED_COLOR_TOKENS.map(({ key, label }) => {
+ const tokenValue = tokenValues[key];
+ return (
+ <TokenRow key={key} data-test={`theme-color-picker-${key}`}>
+ <Typography.Text>{label()}</Typography.Text>
+ <ColorPickerControl
+ ariaLabel={label()}
+ value={typeof tokenValue === 'string' ? tokenValue : undefined}
+ onChange={handleTokenChange(key)}
+ outputFormat="hex"
+ />
+ </TokenRow>
+ );
+ })}
+ </TokenGrid>
+ </div>
+ );
+}
diff --git a/superset-frontend/src/features/themes/ThemeModal.test.tsx b/superset-frontend/src/features/themes/ThemeModal.test.tsx
index 2b4c29efc4f..f5d256a9df6 100644
--- a/superset-frontend/src/features/themes/ThemeModal.test.tsx
+++ b/superset-frontend/src/features/themes/ThemeModal.test.tsx
@@ -866,3 +866,151 @@ test('disables Apply button when JSON configuration is invalid', async () => {
const applyButton = await screen.findByRole('button', { name: /apply/i });
expect(applyButton).toBeDisabled();
});
+
+// Curated color pickers ("Colors" section) -- see ThemeColorPickers.test.tsx
+// for exhaustive coverage of the pure patch/parse helpers; these tests cover
+// the wiring between ThemeModal's JSON textarea and that section.
+test('shows a color picker row for the curated colorPrimary token', () => {
+ render(
+ <ThemeModal
+ addDangerToast={jest.fn()}
+ addSuccessToast={jest.fn()}
+ onThemeAdd={jest.fn()}
+ onHide={jest.fn()}
+ show
+ canDevelop={false}
+ />,
+ { useRedux: true, useRouter: true },
+ );
+
+ expect(screen.getByTestId('theme-color-pickers')).toBeInTheDocument();
+ expect(
+ screen.getByTestId('theme-color-picker-colorPrimary'),
+ ).toBeInTheDocument();
+});
+
+test('does not show the Colors section for read-only system themes', async () => {
+ render(
+ <ThemeModal
+ addDangerToast={jest.fn()}
+ addSuccessToast={jest.fn()}
+ onThemeAdd={jest.fn()}
+ onHide={jest.fn()}
+ show
+ canDevelop={false}
+ theme={mockSystemTheme}
+ />,
+ { useRedux: true, useRouter: true },
+ );
+
+ await screen.findByText('System Theme - Read Only');
+
+ expect(screen.queryByTestId('theme-color-pickers')).not.toBeInTheDocument();
+});
+
+test('editing the JSON textarea updates the matching color picker (JSON -> pickers sync)', async () => {
+ render(
+ <ThemeModal
+ addDangerToast={jest.fn()}
+ addSuccessToast={jest.fn()}
+ onThemeAdd={jest.fn()}
+ onHide={jest.fn()}
+ show
+ canDevelop={false}
+ />,
+ { useRedux: true, useRouter: true },
+ );
+
+ const jsonEditor = screen.getByTestId('json-editor');
+ await userEvent.clear(jsonEditor);
+ await userEvent.type(
+ jsonEditor,
+ JSON.stringify({ token: { colorPrimary: '#336699' } }),
+ );
+
+ await waitFor(() => {
+ const swatch = screen
+ .getByTestId('theme-color-picker-colorPrimary')
+ .querySelector('.ant-color-picker-color-block-inner') as HTMLElement;
+ expect(swatch.style.background).toContain('51, 102, 153'); // #336699
+ });
+});
+
+test('a token present only in the JSON, not in the curated list, survives a picker edit untouched', async () => {
+ render(
+ <ThemeModal
+ addDangerToast={jest.fn()}
+ addSuccessToast={jest.fn()}
+ onThemeAdd={jest.fn()}
+ onHide={jest.fn()}
+ show
+ canDevelop={false}
+ />,
+ { useRedux: true, useRouter: true },
+ );
+
+ const jsonEditor = screen.getByTestId('json-editor');
+ await userEvent.clear(jsonEditor);
+ await userEvent.type(
+ jsonEditor,
+ JSON.stringify({
+ token: { colorPrimary: '#1890ff', borderRadiusLG: 12 },
+ }),
+ );
+
+ await waitFor(() => {
+ expect(jsonEditor).toHaveValue(
+ JSON.stringify({
+ token: { colorPrimary: '#1890ff', borderRadiusLG: 12 },
+ }),
+ );
+ });
+
+ const trigger = screen
+ .getByTestId('theme-color-picker-colorSuccess')
+ .querySelector('.ant-color-picker-trigger');
+ await userEvent.click(trigger!);
+
+ await waitFor(() => {
+ expect(document.querySelector('.ant-color-picker')).toBeInTheDocument();
+ });
+ const hexInput = document.querySelector<HTMLInputElement>(
+ '.ant-color-picker-input input',
+ );
+ await userEvent.clear(hexInput!);
+ await userEvent.type(hexInput!, '00ff00{enter}');
+
+ await waitFor(() => {
+ const parsed = JSON.parse((jsonEditor as HTMLTextAreaElement).value);
+ expect(parsed.token.colorSuccess.toLowerCase()).toBe('#00ff00');
+ // uncurated token untouched by the picker -> JSON patch
+ expect(parsed.token.borderRadiusLG).toBe(12);
+ expect(parsed.token.colorPrimary).toBe('#1890ff');
+ });
+});
+
+test('does not crash and shows the invalid-JSON notice while the JSON textarea is mid-edit', async () => {
+ render(
+ <ThemeModal
+ addDangerToast={jest.fn()}
+ addSuccessToast={jest.fn()}
+ onThemeAdd={jest.fn()}
+ onHide={jest.fn()}
+ show
+ canDevelop={false}
+ />,
+ { useRedux: true, useRouter: true },
+ );
+
+ const jsonEditor = screen.getByTestId('json-editor');
+ await userEvent.clear(jsonEditor);
+ await userEvent.type(jsonEditor, '{ "token": { "colorPrimary"');
+
+ await waitFor(() => {
+ expect(
+ screen.getByTestId('theme-color-pickers-invalid-json-notice'),
+ ).toBeInTheDocument();
+ });
+ // the modal itself is still usable -- name field etc. still present
+ expect(screen.getByPlaceholderText('Enter theme name')).toBeInTheDocument();
+});
diff --git a/superset-frontend/src/features/themes/ThemeModal.tsx b/superset-frontend/src/features/themes/ThemeModal.tsx
index 7c591a0eb64..031233d244e 100644
--- a/superset-frontend/src/features/themes/ThemeModal.tsx
+++ b/superset-frontend/src/features/themes/ThemeModal.tsx
@@ -50,6 +50,7 @@ import { Typography } from '@superset-ui/core/components/Typography';
import { useThemeValidation } from 'src/theme/hooks/useThemeValidation';
import { OnlyKeyWithType } from 'src/utils/types';
import { ThemeObject } from './types';
+import ThemeColorPickers from './ThemeColorPickers';
type EditorAnnotation = editors.EditorAnnotation;
@@ -498,6 +499,15 @@ const ThemeModal: FunctionComponent<ThemeModalProps> = ({
/>
</Form.Item>
+ {!isReadOnly && (
+ <Form.Item label={t('Colors')}>
+ <ThemeColorPickers
+ jsonData={currentTheme?.json_data || ''}
+ onChange={onJsonDataChange}
+ />
+ </Form.Item>
+ )}
+
<Form.Item label={t('JSON Configuration')} required={!isReadOnly}>
<Alert
type="info"
(superset) 03/04: feat(big-number): replace 2-choice comparison scheme with color pickers
Posted by ru...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch feat/color-picker-consolidation
in repository https://gitbox.apache.org/repos/asf/superset.git
commit c410906061dc2e4b2f06cb93a6969ef4c105acda
Author: Claude Code <no...@anthropic.com>
AuthorDate: Fri Aug 7 23:44:56 2026 -0700
feat(big-number): replace 2-choice comparison scheme with color pickers
The Period-over-Period Big Number's "color scheme for comparison"
control only offered two fixed choices ("Green for increase, red for
decrease" and its reverse), bound directly to theme.colorSuccess /
theme.colorError with no room for a brand-specific color.
Replace it with two ColorPickerControls, `increase_color` and
`decrease_color` (defaulting to the 'Green' / 'Red' semantic tokens,
matching the historical default), using the same resolveThemeTokens +
outputFormat="hex" pattern #42053 introduced for
FormattingPopoverContent: picking the "Green"/"Red" preset swatch
stores the token name (so the UI still reads the same as before for
users who just want the classic behavior), while any other pick stores
a literal hex color.
`increaseColor`/`decreaseColor` and the color->style resolution move
to two small, independently unit-tested pure functions in utils.ts
(`resolveComparisonColorKeys`, `getComparisonColorTokens`) rather than
living inline in PopKPI's render body, since jsdom doesn't reliably
expose emotion's injected styles to `toHaveStyle` for direct
component-level assertions.
Backward compatibility: `resolveComparisonColorKeys` falls back to the
legacy `comparisonColorScheme` field (still read, marked @deprecated in
types.ts) whenever the new fields are absent, including correctly
reversing increase/decrease for charts saved with the old "Red for
increase, green for decrease" choice -- the case a naive
default-to-Green migration would have silently broken.
Also exports `SPECIAL_COLORS/SpecialColorKey` from ColorPickerControl
so other call sites (like this one) don't need to redefine the
Green/Red semantic color mapping.
---
.../BigNumberPeriodOverPeriod/PopKPI.test.tsx | 106 +++++++++++++++++++++
.../BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx | 59 +++++++-----
.../BigNumberPeriodOverPeriod/controlPanel.ts | 43 +++++++--
.../BigNumberPeriodOverPeriod/transformProps.ts | 4 +
.../BigNumber/BigNumberPeriodOverPeriod/types.ts | 14 +++
.../BigNumberPeriodOverPeriod/utils.test.ts | 70 +++++++++++++-
.../BigNumber/BigNumberPeriodOverPeriod/utils.ts | 74 ++++++++++++++
.../components/controls/ColorPickerControl.tsx | 4 +-
8 files changed, 338 insertions(+), 36 deletions(-)
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.test.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.test.tsx
new file mode 100644
index 00000000000..cdf3ddc9af9
--- /dev/null
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.test.tsx
@@ -0,0 +1,106 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen } from 'spec/helpers/testing-library';
+import PopKPI from './PopKPI';
+import { PopKPIProps } from './types';
+
+const baseProps: PopKPIProps = {
+ height: 200,
+ width: 400,
+ data: [],
+ metrics: [],
+ metricName: 'Sales',
+ showMetricName: true,
+ headerText: '',
+ boldText: true,
+ bigNumber: '120',
+ prevNumber: '100',
+ valueDifference: '20',
+ percentDifferenceFormattedString: '20%',
+ compType: 'r',
+ percentDifferenceNumber: 0.2,
+ subtitleFontSize: 0.15,
+ shift: '',
+ headerFontSize: 'l',
+ subheaderFontSize: 'm',
+ comparisonColorEnabled: true,
+};
+
+test('renders the up arrow and metric values when the metric increased', () => {
+ render(<PopKPI {...baseProps} />);
+
+ expect(screen.getByText('↑')).toBeInTheDocument();
+ expect(screen.getByText('120')).toBeInTheDocument();
+ expect(screen.getByText('Sales')).toBeInTheDocument();
+});
+
+test('renders the down arrow when the metric decreased', () => {
+ render(
+ <PopKPI
+ {...baseProps}
+ percentDifferenceNumber={-0.2}
+ valueDifference="-20"
+ />,
+ );
+
+ expect(screen.getByText('↓')).toBeInTheDocument();
+});
+
+// The precise color resolution (legacy `comparisonColorScheme` fallback,
+// custom hex precedence, the neutral disabled state) is covered by pure
+// unit tests against `resolveComparisonColorKeys` / `getComparisonColorTokens`
+// in utils.test.ts, since emotion's `css` prop styles aren't reliably
+// observable through jsdom's computed styles. These tests instead confirm
+// PopKPI renders without crashing across the same prop combinations.
+test('renders without crashing with only the legacy comparisonColorScheme (backward compatibility)', () => {
+ render(<PopKPI {...baseProps} comparisonColorScheme="Red" />);
+
+ expect(screen.getByText('↑')).toBeInTheDocument();
+});
+
+test('renders without crashing with a custom increaseColor hex', () => {
+ render(
+ <PopKPI
+ {...baseProps}
+ comparisonColorScheme="Red"
+ increaseColor="#336699"
+ />,
+ );
+
+ expect(screen.getByText('↑')).toBeInTheDocument();
+});
+
+test('renders without crashing when comparisonColorEnabled is false', () => {
+ render(
+ <PopKPI
+ {...baseProps}
+ comparisonColorEnabled={false}
+ increaseColor="#336699"
+ />,
+ );
+
+ expect(screen.getByText('↑')).toBeInTheDocument();
+});
+
+test('no arrow renders when there is no difference', () => {
+ render(<PopKPI {...baseProps} percentDifferenceNumber={0} />);
+
+ expect(screen.queryByText('↑')).not.toBeInTheDocument();
+ expect(screen.queryByText('↓')).not.toBeInTheDocument();
+});
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx
index 4af6f5d221e..f96d6339ba4 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/PopKPI.tsx
@@ -25,10 +25,7 @@ import {
} from '@superset-ui/core';
import { css, styled, useTheme } from '@apache-superset/core/theme';
import { Tooltip } from '@superset-ui/core/components';
-import {
- DEFAULT_DATE_PATTERN,
- ColorSchemeEnum,
-} from '@superset-ui/chart-controls';
+import { DEFAULT_DATE_PATTERN } from '@superset-ui/chart-controls';
import { isEmpty } from 'lodash-es';
import {
PopKPIComparisonSymbolStyleProps,
@@ -36,6 +33,7 @@ import {
PopKPIProps,
} from './types';
import { useOverflowDetection } from './useOverflowDetection';
+import { getComparisonColorTokens, resolveComparisonColorKeys } from './utils';
const MetricNameText = styled.div<{ metricNameFontSize?: number }>`
${({ theme, metricNameFontSize }) => `
@@ -92,6 +90,8 @@ export default function PopKPI(props: PopKPIProps) {
subheaderFontSize,
comparisonColorEnabled,
comparisonColorScheme,
+ increaseColor,
+ decreaseColor,
percentDifferenceNumber,
currentTimeRangeFilter,
startDateOffset,
@@ -167,21 +167,29 @@ export default function PopKPI(props: PopKPIProps) {
`}
`;
+ // `increase_color` / `decrease_color` (ColorPickerControl, added after the
+ // original 2-choice `comparison_color_scheme` select) hold either a
+ // semantic token name ('Green' | 'Red') or a literal hex color; see
+ // `resolveComparisonColorKeys` in utils.ts for how charts saved before
+ // those controls existed keep rendering with the same colors.
+ const {
+ increaseColor: resolvedIncreaseColor,
+ decreaseColor: resolvedDecreaseColor,
+ } = resolveComparisonColorKeys(
+ comparisonColorScheme,
+ increaseColor,
+ decreaseColor,
+ );
+
const getArrowIndicatorColor = () => {
if (!comparisonColorEnabled || percentDifferenceNumber === 0) {
return theme.colorTextTertiary;
}
-
- if (percentDifferenceNumber > 0) {
- // Positive difference
- return comparisonColorScheme === ColorSchemeEnum.Green
- ? theme.colorSuccess
- : theme.colorError;
- }
- // Negative difference
- return comparisonColorScheme === ColorSchemeEnum.Red
- ? theme.colorSuccess
- : theme.colorError;
+ const colorValue =
+ percentDifferenceNumber > 0
+ ? resolvedIncreaseColor
+ : resolvedDecreaseColor;
+ return getComparisonColorTokens(colorValue, theme).text;
};
const arrowIndicatorStyle = css`
@@ -195,15 +203,13 @@ export default function PopKPI(props: PopKPIProps) {
let bgColor = defaultBackgroundColor;
let txtColor = defaultTextColor;
if (comparisonColorEnabled && percentDifferenceNumber !== 0) {
- const useSuccess =
- (percentDifferenceNumber > 0 &&
- comparisonColorScheme === ColorSchemeEnum.Green) ||
- (percentDifferenceNumber < 0 &&
- comparisonColorScheme === ColorSchemeEnum.Red);
-
- // Set background and text colors based on the conditions
- bgColor = useSuccess ? theme.colorSuccessBg : theme.colorErrorBg;
- txtColor = useSuccess ? theme.colorSuccessText : theme.colorErrorText;
+ const colorValue =
+ percentDifferenceNumber > 0
+ ? resolvedIncreaseColor
+ : resolvedDecreaseColor;
+ const tokens = getComparisonColorTokens(colorValue, theme);
+ bgColor = tokens.background;
+ txtColor = tokens.strongText;
}
return {
@@ -212,9 +218,12 @@ export default function PopKPI(props: PopKPIProps) {
};
}, [
theme,
- comparisonColorScheme,
+ resolvedIncreaseColor,
+ resolvedDecreaseColor,
comparisonColorEnabled,
percentDifferenceNumber,
+ defaultBackgroundColor,
+ defaultTextColor,
]);
const SYMBOLS_WITH_VALUES = useMemo(
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts
index b11d373324a..022e591cdd2 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/controlPanel.ts
@@ -100,21 +100,48 @@ const config: ControlPanelConfig = {
],
[
{
- name: 'comparison_color_scheme',
+ name: 'increase_color',
config: {
- type: 'SelectControl',
- label: t('color scheme for comparison'),
+ type: 'ColorPickerControl',
+ label: t('Color for increase'),
default: ColorSchemeEnum.Green,
renderTrigger: true,
- choices: [
- [ColorSchemeEnum.Green, 'Green for increase, red for decrease'],
- [ColorSchemeEnum.Red, 'Red for increase, green for decrease'],
+ presets: [
+ {
+ label: t('Semantic colors'),
+ colors: [ColorSchemeEnum.Green, ColorSchemeEnum.Red],
+ },
],
+ resolveThemeTokens: true,
+ outputFormat: 'hex',
visibility: ({ controls }) =>
controls?.comparison_color_enabled?.value === true,
description: t(
- 'Adds color to the chart symbols based on the positive or ' +
- 'negative change from the comparison value.',
+ 'Color used for the arrow and symbols when the metric ' +
+ 'increased from the comparison value. Defaults to green.',
+ ),
+ },
+ },
+ {
+ name: 'decrease_color',
+ config: {
+ type: 'ColorPickerControl',
+ label: t('Color for decrease'),
+ default: ColorSchemeEnum.Red,
+ renderTrigger: true,
+ presets: [
+ {
+ label: t('Semantic colors'),
+ colors: [ColorSchemeEnum.Green, ColorSchemeEnum.Red],
+ },
+ ],
+ resolveThemeTokens: true,
+ outputFormat: 'hex',
+ visibility: ({ controls }) =>
+ controls?.comparison_color_enabled?.value === true,
+ description: t(
+ 'Color used for the arrow and symbols when the metric ' +
+ 'decreased from the comparison value. Defaults to red.',
),
},
},
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
index 70e8702fb8d..b2fd9c5ad84 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/transformProps.ts
@@ -99,6 +99,8 @@ export default function transformProps(chartProps: ChartProps) {
subheaderFontSize,
comparisonColorScheme,
comparisonColorEnabled,
+ increaseColor,
+ decreaseColor,
percentDifferenceFormat,
subtitle = '',
subtitleFontSize,
@@ -225,6 +227,8 @@ export default function transformProps(chartProps: ChartProps) {
compType,
comparisonColorEnabled,
comparisonColorScheme,
+ increaseColor,
+ decreaseColor,
percentDifferenceNumber: percentDifferenceNum,
currentTimeRangeFilter,
startDateOffset,
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/types.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/types.ts
index 7503de4c7d0..2cb37dd5748 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/types.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/types.ts
@@ -72,7 +72,21 @@ export type PopKPIProps = PopKPIStylesProps &
percentDifferenceFormattedString: string;
compType: string;
percentDifferenceNumber: number;
+ /**
+ * @deprecated Superset versions before `increaseColor`/`decreaseColor`
+ * existed stored a single 2-choice scheme ('Green' | 'Red') here. Still
+ * read at render time (see `PopKPI.tsx`) whenever the newer fields are
+ * absent, so charts saved with this shape keep rendering identically.
+ */
comparisonColorScheme?: string;
+ /** Color used for the arrow/symbols when the metric increased. Either a
+ * semantic token name ('Green' | 'Red') or a literal hex color chosen
+ * via the `increase_color` ColorPickerControl. */
+ increaseColor?: string;
+ /** Color used for the arrow/symbols when the metric decreased. Either a
+ * semantic token name ('Green' | 'Red') or a literal hex color chosen
+ * via the `decrease_color` ColorPickerControl. */
+ decreaseColor?: string;
currentTimeRangeFilter?: SimpleAdhocFilter;
startDateOffset?: string;
shift: string;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.test.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.test.ts
index 60dea80a7af..c3b803454a3 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.test.ts
@@ -16,7 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { getComparisonFontSize, getHeaderFontSize } from './utils';
+import { supersetTheme } from '@apache-superset/core/theme';
+import {
+ getComparisonColorTokens,
+ getComparisonFontSize,
+ getHeaderFontSize,
+ resolveComparisonColorKeys,
+} from './utils';
test('getHeaderFontSize', () => {
expect(getHeaderFontSize(0.2)).toEqual(16);
@@ -37,3 +43,65 @@ test('getComparisonFontSize', () => {
expect(getComparisonFontSize(0.05)).toEqual(40);
expect(getComparisonFontSize(0.9)).toEqual(40);
});
+
+test('resolveComparisonColorKeys defaults to Green/Red when nothing is set', () => {
+ expect(resolveComparisonColorKeys(undefined, undefined, undefined)).toEqual({
+ increaseColor: 'Green',
+ decreaseColor: 'Red',
+ });
+});
+
+test('resolveComparisonColorKeys honors the new increase_color/decrease_color controls', () => {
+ expect(resolveComparisonColorKeys(undefined, '#ff0000', '#00ff00')).toEqual({
+ increaseColor: '#ff0000',
+ decreaseColor: '#00ff00',
+ });
+});
+
+test('resolveComparisonColorKeys falls back to the legacy Green comparison_color_scheme', () => {
+ // legacy default: "Green for increase, red for decrease"
+ expect(resolveComparisonColorKeys('Green', undefined, undefined)).toEqual({
+ increaseColor: 'Green',
+ decreaseColor: 'Red',
+ });
+});
+
+test('resolveComparisonColorKeys reverses colors for the legacy Red comparison_color_scheme', () => {
+ // legacy reversed choice: "Red for increase, green for decrease" -- this
+ // is the case a naive default-to-Green migration would silently break.
+ expect(resolveComparisonColorKeys('Red', undefined, undefined)).toEqual({
+ increaseColor: 'Red',
+ decreaseColor: 'Green',
+ });
+});
+
+test('resolveComparisonColorKeys prefers the new fields over the legacy scheme when both are present', () => {
+ expect(resolveComparisonColorKeys('Red', '#ff0000', undefined)).toEqual({
+ increaseColor: '#ff0000',
+ decreaseColor: 'Green',
+ });
+});
+
+test('getComparisonColorTokens resolves the Green semantic token to theme success colors', () => {
+ expect(getComparisonColorTokens('Green', supersetTheme)).toEqual({
+ text: supersetTheme.colorSuccess,
+ background: supersetTheme.colorSuccessBg,
+ strongText: supersetTheme.colorSuccessText,
+ });
+});
+
+test('getComparisonColorTokens resolves the Red semantic token to theme error colors', () => {
+ expect(getComparisonColorTokens('Red', supersetTheme)).toEqual({
+ text: supersetTheme.colorError,
+ background: supersetTheme.colorErrorBg,
+ strongText: supersetTheme.colorErrorText,
+ });
+});
+
+test('getComparisonColorTokens treats any other value as a literal hex color', () => {
+ expect(getComparisonColorTokens('#336699', supersetTheme)).toEqual({
+ text: '#336699',
+ background: '#3366991A',
+ strongText: '#336699',
+ });
+});
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.ts b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.ts
index 9b658593298..132ed73b174 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberPeriodOverPeriod/utils.ts
@@ -16,6 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
+import type { SupersetTheme } from '@apache-superset/core/theme';
+import { ColorSchemeEnum } from '@superset-ui/chart-controls';
import {
headerFontSize,
subheaderFontSize,
@@ -74,3 +76,75 @@ export const getHeaderFontSize = (proportionValue: number) =>
export const getComparisonFontSize = (proportionValue: number) =>
comparisonFontSizesMapping[proportionValue] ??
sharedFontSizes[sharedFontSizes.length - 1];
+
+export interface ComparisonColorTokens {
+ /** Color for the arrow indicator and (when the symbol is index 0) text. */
+ text: string;
+ /** Background color for the increase/decrease pill. */
+ background: string;
+ /** Foreground color for the increase/decrease pill's text. */
+ strongText: string;
+}
+
+/**
+ * Resolves the increase/decrease colors to use for rendering, given the
+ * chart's current `increaseColor` / `decreaseColor` (from the
+ * `ColorPickerControl`s added after this became customizable) and the
+ * legacy `comparisonColorScheme` field.
+ *
+ * Charts saved before `increaseColor` / `decreaseColor` existed only have
+ * `comparisonColorScheme`, a 2-choice select ('Green' | 'Red') where 'Green'
+ * meant "green for increase, red for decrease" and 'Red' meant the reverse.
+ * Both legacy choices map onto the same 'Green' | 'Red' semantic token names
+ * used by the new controls' presets, so resolving through it here
+ * reproduces the exact old behavior (including the reversed case) without a
+ * data migration.
+ */
+export const resolveComparisonColorKeys = (
+ comparisonColorScheme: string | undefined,
+ increaseColor: string | undefined,
+ decreaseColor: string | undefined,
+): { increaseColor: string; decreaseColor: string } => {
+ const legacyReversed = comparisonColorScheme === ColorSchemeEnum.Red;
+ return {
+ increaseColor:
+ increaseColor ??
+ (legacyReversed ? ColorSchemeEnum.Red : ColorSchemeEnum.Green),
+ decreaseColor:
+ decreaseColor ??
+ (legacyReversed ? ColorSchemeEnum.Green : ColorSchemeEnum.Red),
+ };
+};
+
+/**
+ * Resolves a single color value (semantic token name or literal hex from
+ * the color picker) to the (arrow/text, background, strong-text) triad used
+ * across the comparison pills. 'Green' / 'Red' keep using the paired
+ * success/error theme tokens exactly as before these colors were
+ * customizable; any other value is a literal hex, in which case the
+ * background is a light (~10% opacity) tint of that same color.
+ */
+export const getComparisonColorTokens = (
+ colorValue: string,
+ theme: SupersetTheme,
+): ComparisonColorTokens => {
+ if (colorValue === ColorSchemeEnum.Green) {
+ return {
+ text: theme.colorSuccess,
+ background: theme.colorSuccessBg,
+ strongText: theme.colorSuccessText,
+ };
+ }
+ if (colorValue === ColorSchemeEnum.Red) {
+ return {
+ text: theme.colorError,
+ background: theme.colorErrorBg,
+ strongText: theme.colorErrorText,
+ };
+ }
+ return {
+ text: colorValue,
+ background: `${colorValue}1A`,
+ strongText: colorValue,
+ };
+};
diff --git a/superset-frontend/src/explore/components/controls/ColorPickerControl.tsx b/superset-frontend/src/explore/components/controls/ColorPickerControl.tsx
index cdbb83aeb45..86664360a59 100644
--- a/superset-frontend/src/explore/components/controls/ColorPickerControl.tsx
+++ b/superset-frontend/src/explore/components/controls/ColorPickerControl.tsx
@@ -27,12 +27,12 @@ import {
import ControlHeader from '../ControlHeader';
import { useTheme, type SupersetTheme } from '@apache-superset/core/theme';
-const SPECIAL_COLORS = {
+export const SPECIAL_COLORS = {
Red: { r: 150, g: 0, b: 0, a: 0.2 },
Green: { r: 0, g: 150, b: 0, a: 0.2 },
} as const;
-type SpecialColorKey = keyof typeof SPECIAL_COLORS;
+export type SpecialColorKey = keyof typeof SPECIAL_COLORS;
export type ColorPickerValue = RGBColor | SpecialColorKey | string;
export type ColorOutputFormat = 'hex' | 'rgb';
(superset) 02/04: feat(bullet): add optional per-range band colors
Posted by ru...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch feat/color-picker-consolidation
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 9ef9005c84bfd75ae84f8340dfcc6b3ee3f1eb5d
Author: Claude Code <no...@anthropic.com>
AuthorDate: Fri Aug 7 23:34:39 2026 -0700
feat(bullet): add optional per-range band colors
The Bullet chart's background range bands were hardcoded to a 4-step
theme-token ramp (colorFillQuaternary -> colorFill) with no way to
customize them, unlike the rest of the chart (ranges, markers, marker
lines) which are all user-configurable.
Add an optional `range_colors` control (BulletRangeColorsControl) that
renders one ColorPickerControl per threshold parsed from the existing
`ranges` control. Each row starts unset ("use default") with a "Use
default" link to clear a customization once made; unset rows keep
using the theme-token ramp exactly as before.
`Bullet/transformProps.ts` captures each range's chosen color
(matched by its original, pre-sort position in `ranges`) before the
existing largest-first band sort reorders them for nested drawing, so
colors stay pinned to the correct threshold regardless of draw order.
Backward compatible by construction: `range_colors` is optional and
defaults to empty, so Bullet charts saved before this control existed
have no such field and render with the exact same default ramp.
---
.../src/Bullet/controlPanel.tsx | 24 ++++-
.../src/Bullet/transformProps.ts | 17 ++-
.../plugin-chart-echarts/src/Bullet/types.ts | 8 ++
.../test/Bullet/transformProps.test.ts | 47 ++++++++
.../BulletRangeColorsControl.test.tsx | 119 +++++++++++++++++++++
.../controls/BulletRangeColorsControl/index.tsx | 114 ++++++++++++++++++++
.../controls/BulletRangeColorsControl/types.ts | 34 ++++++
.../src/explore/components/controls/index.ts | 2 +
8 files changed, 361 insertions(+), 4 deletions(-)
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/controlPanel.tsx
index 14790e6e736..049d5fffcf0 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/controlPanel.tsx
@@ -17,7 +17,10 @@
* under the License.
*/
import { t } from '@apache-superset/core/translation';
-import { ControlPanelConfig } from '@superset-ui/chart-controls';
+import {
+ ControlPanelConfig,
+ ControlPanelState,
+} from '@superset-ui/chart-controls';
// Control names match the legacy nvd3 bullet chart so saved charts keep
// working without a form-data migration.
@@ -59,6 +62,25 @@ const config: ControlPanelConfig = {
},
},
],
+ [
+ {
+ name: 'range_colors',
+ config: {
+ type: 'BulletRangeColorsControl',
+ label: t('Range colors'),
+ default: [],
+ renderTrigger: true,
+ description: t(
+ 'Optional custom color for each range band, e.g. to match a brand palette. Bands left unset use the default shading.',
+ ),
+ visibility: ({ controls }) => Boolean(controls?.ranges?.value),
+ shouldMapStateToProps: () => true,
+ mapStateToProps: (state: ControlPanelState) => ({
+ ranges: state?.controls?.ranges?.value as string,
+ }),
+ },
+ },
+ ],
[
{
name: 'markers',
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts
index de7eb3b2c36..0a16df307cc 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/transformProps.ts
@@ -45,6 +45,7 @@ export default function transformProps(
groupby,
ranges: rawRanges,
rangeLabels: rawRangeLabels,
+ rangeColors,
markers: rawMarkers,
markerLabels: rawMarkerLabels,
markerLines: rawMarkerLines,
@@ -102,17 +103,27 @@ export default function transformProps(
theme.colorFillSecondary,
theme.colorFill,
];
+ // Custom colors (if any) are authored positionally against the original,
+ // pre-sort `ranges` order via the `range_colors` control -- capture each
+ // range's color here, before the descending sort below reorders them.
const sortedRanges = [...ranges]
- .map((value, i) => ({ value, label: rangeLabels[i] }))
+ .map((value, i) => ({
+ value,
+ label: rangeLabels[i],
+ color: rangeColors?.[i] || undefined,
+ }))
.filter(({ value }) => value > axisMin)
.sort((a, b) => b.value - a.value);
// Each band's label sits inside its own top-right corner: the visible strip
// of a nested band ends at its threshold, so the label lands inside the
// range it names and the rightmost label cannot clip at the chart edge.
- const bands = sortedRanges.map(({ value, label }, i) => ({
+ const bands = sortedRanges.map(({ value, label, color }, i) => ({
name: label,
itemStyle: {
- color: bandFills[Math.min(i, bandFills.length - 1)],
+ // A custom `range_colors` entry wins; otherwise fall back to the
+ // default theme-token ramp exactly as before this control existed, so
+ // Bullet charts saved without `range_colors` are unaffected.
+ color: color || bandFills[Math.min(i, bandFills.length - 1)],
},
label: {
show: Boolean(showLabels) && Boolean(label),
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/types.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/types.ts
index d57e8ab7a2f..7c2db1eb28c 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/types.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Bullet/types.ts
@@ -34,6 +34,14 @@ export type EchartsBulletFormData = QueryFormData & {
/** Comma-separated threshold values shaded as background bands */
ranges?: string;
rangeLabels?: string;
+ /**
+ * Optional per-range fill colors (hex), positionally matched to the
+ * thresholds parsed from `ranges`. An empty string (or a missing entry)
+ * means "no custom color" -- that band falls back to the default
+ * theme-token ramp. Absent entirely on charts saved before this control
+ * existed, which keeps them rendering identically.
+ */
+ rangeColors?: string[];
/** Comma-separated values drawn as point markers */
markers?: string;
markerLabels?: string;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts
index 306db08e527..28dbc4f24f1 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/test/Bullet/transformProps.test.ts
@@ -256,3 +256,50 @@ test('splits into one bullet row per group value with shared markers', () => {
// grouped bar tooltips name the row
expect(series[0].tooltip.formatter({ dataIndex: 1 })).toContain('NY');
});
+
+test('applies custom range_colors to their bands, matched by original (pre-sort) range order', () => {
+ const { echartOptions } = transformProps(
+ chartProps({ rangeColors: ['#ff0000', '#00ff00', '#0000ff'] }),
+ );
+ const { series } = echartOptions as any;
+
+ // bands are drawn largest-threshold-first (300, 200, 100), but colors
+ // must stay pinned to their original range value (100 -> red, 200 ->
+ // green, 300 -> blue), not to the post-sort draw order.
+ const bandColors = series[0].markArea.data.map(
+ (d: any) => d[0].itemStyle.color,
+ );
+ expect(bandColors).toEqual(['#0000ff', '#00ff00', '#ff0000']);
+});
+
+test('falls back to the default theme-token ramp when range_colors is absent (backward compatibility)', () => {
+ const { echartOptions } = transformProps(chartProps());
+ const { series } = echartOptions as any;
+
+ const bandColors = series[0].markArea.data.map(
+ (d: any) => d[0].itemStyle.color,
+ );
+ expect(bandColors).toEqual([
+ supersetTheme.colorFillQuaternary,
+ supersetTheme.colorFillTertiary,
+ supersetTheme.colorFillSecondary,
+ ]);
+});
+
+test('falls back to the default ramp for individual ranges left unset in range_colors', () => {
+ const { echartOptions } = transformProps(
+ chartProps({ rangeColors: ['', '#00ff00', ''] }),
+ );
+ const { series } = echartOptions as any;
+
+ const bandColors = series[0].markArea.data.map(
+ (d: any) => d[0].itemStyle.color,
+ );
+ // draw order is 300, 200, 100 -> only the 200 threshold (index 1) has a
+ // custom color; the other two fall back to the ramp at their draw index.
+ expect(bandColors).toEqual([
+ supersetTheme.colorFillQuaternary,
+ '#00ff00',
+ supersetTheme.colorFillSecondary,
+ ]);
+});
diff --git a/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/BulletRangeColorsControl.test.tsx b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/BulletRangeColorsControl.test.tsx
new file mode 100644
index 00000000000..e5afb1dd7bd
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/BulletRangeColorsControl.test.tsx
@@ -0,0 +1,119 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
+import BulletRangeColorsControl from 'src/explore/components/controls/BulletRangeColorsControl';
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+test('renders a hint and no rows when no ranges are configured', () => {
+ render(<BulletRangeColorsControl onChange={jest.fn()} />);
+
+ expect(
+ screen.getByText('Add ranges above to configure their colors here.'),
+ ).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 0,
+ );
+});
+
+test('renders one color picker row per parsed range, unset by default', () => {
+ render(
+ <BulletRangeColorsControl onChange={jest.fn()} ranges="100,200,300" />,
+ );
+
+ expect(screen.getByText(/Up to 100/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 200/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 300/)).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 3,
+ );
+ // no row has a custom color yet, so no "Use default" reset link shows
+ expect(screen.queryByText('Use default')).not.toBeInTheDocument();
+});
+
+test('shows a "Use default" reset link only for rows with a custom color', () => {
+ render(
+ <BulletRangeColorsControl
+ onChange={jest.fn()}
+ ranges="100,200"
+ value={['#ff0000', '']}
+ />,
+ );
+
+ expect(screen.getAllByText('Use default')).toHaveLength(1);
+});
+
+test('calls onChange with the full color array when a row color is picked', async () => {
+ const onChange = jest.fn();
+ render(
+ <BulletRangeColorsControl
+ onChange={onChange}
+ ranges="100,200"
+ value={['', '']}
+ />,
+ );
+
+ const triggers = document.querySelectorAll('.ant-color-picker-trigger');
+ expect(triggers).toHaveLength(2);
+
+ await userEvent.click(triggers[0]);
+ await waitFor(() => {
+ expect(document.querySelector('.ant-color-picker')).toBeInTheDocument();
+ });
+
+ const hexInput = document.querySelector<HTMLInputElement>(
+ '.ant-color-picker-input input',
+ );
+ expect(hexInput).toBeInTheDocument();
+ await userEvent.clear(hexInput!);
+ await userEvent.type(hexInput!, '00ff00{enter}');
+
+ await waitFor(() => {
+ expect(onChange).toHaveBeenCalled();
+ });
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0];
+ expect(lastCall[0].toLowerCase()).toBe('#00ff00');
+ expect(lastCall[1]).toBe('');
+});
+
+test('resets a single row back to "no custom color" without touching the others', () => {
+ const onChange = jest.fn();
+ render(
+ <BulletRangeColorsControl
+ onChange={onChange}
+ ranges="100,200"
+ value={['#ff0000', '#00ff00']}
+ />,
+ );
+
+ const resetButtons = screen.getAllByText('Use default');
+ expect(resetButtons).toHaveLength(2);
+ userEvent.click(resetButtons[0]);
+
+ return waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith(['', '#00ff00']);
+ });
+});
diff --git a/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/index.tsx b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/index.tsx
new file mode 100644
index 00000000000..b3ea2ae9e8e
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/index.tsx
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { styled } from '@apache-superset/core/theme';
+import { Button } from '@superset-ui/core/components';
+import ControlHeader from '../../ControlHeader';
+import ColorPickerControl from '../ColorPickerControl';
+import type { ColorPickerValue } from '../ColorPickerControl';
+import { BulletRangeColorsControlProps } from './types';
+
+const RangeRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: ${({ theme }) => theme.sizeUnit * 2}px;
+ margin-bottom: ${({ theme }) => theme.sizeUnit}px;
+`;
+
+const RangeLabel = styled.span`
+ min-width: 90px;
+ color: ${({ theme }) => theme.colorTextSecondary};
+ font-size: ${({ theme }) => theme.fontSizeSM}px;
+`;
+
+const parseRanges = (ranges?: string): number[] =>
+ (ranges ?? '')
+ .split(',')
+ .map(part => part.trim())
+ .filter(part => part !== '')
+ .map(Number)
+ .filter(range => Number.isFinite(range));
+
+/**
+ * Per-range color editor for the Bullet chart. Row *count* is driven by the
+ * sibling `ranges` control (one row per parsed threshold) so range values
+ * keep a single source of truth; this control only owns colors, stored as
+ * an array of hex strings positionally matched to those thresholds. An
+ * empty string entry (or a missing entry past the end of the array) means
+ * "no custom color" -- `Bullet/transformProps.ts` falls back to the default
+ * theme-token band ramp for that range, so existing saved Bullet charts
+ * (which have no `range_colors` at all) render identically to before this
+ * control existed.
+ */
+export default function BulletRangeColorsControl({
+ value,
+ onChange,
+ ranges,
+ ...headerProps
+}: BulletRangeColorsControlProps) {
+ const rangeValues = parseRanges(ranges);
+
+ const colorAt = (index: number): string => value?.[index] || '';
+
+ const handleColorChange = (index: number) => (color: ColorPickerValue) => {
+ if (typeof color !== 'string') return;
+ const next = rangeValues.map((_, i) => (i === index ? color : colorAt(i)));
+ onChange?.(next);
+ };
+
+ const handleReset = (index: number) => {
+ const next = rangeValues.map((_, i) => (i === index ? '' : colorAt(i)));
+ onChange?.(next);
+ };
+
+ return (
+ <div>
+ <ControlHeader {...headerProps} />
+ {rangeValues.length === 0 ? (
+ <RangeLabel>
+ {t('Add ranges above to configure their colors here.')}
+ </RangeLabel>
+ ) : (
+ rangeValues.map((range, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <RangeRow key={index}>
+ <RangeLabel>
+ {t('Up to')} {range}
+ </RangeLabel>
+ <ColorPickerControl
+ ariaLabel={t('Color for range up to %s', range)}
+ value={colorAt(index) || undefined}
+ onChange={handleColorChange(index)}
+ outputFormat="hex"
+ />
+ {colorAt(index) && (
+ <Button
+ buttonSize="small"
+ buttonStyle="link"
+ onClick={() => handleReset(index)}
+ >
+ {t('Use default')}
+ </Button>
+ )}
+ </RangeRow>
+ ))
+ )}
+ </div>
+ );
+}
diff --git a/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/types.ts b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/types.ts
new file mode 100644
index 00000000000..57f23cba9f1
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/BulletRangeColorsControl/types.ts
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+export interface BulletRangeColorsControlProps {
+ value?: string[];
+ onChange?: (value: string[]) => void;
+ label?: string;
+ description?: string;
+ hovered?: boolean;
+ renderTrigger?: boolean;
+ warning?: string;
+ /**
+ * Live value of the sibling `ranges` control (comma-separated thresholds),
+ * supplied via `mapStateToProps`. Drives how many color rows are
+ * rendered -- one per parsed range value -- so thresholds stay authored in
+ * a single place (the existing `ranges` text control).
+ */
+ ranges?: string;
+}
diff --git a/superset-frontend/src/explore/components/controls/index.ts b/superset-frontend/src/explore/components/controls/index.ts
index 69e8942cdc2..cfe094b1205 100644
--- a/superset-frontend/src/explore/components/controls/index.ts
+++ b/superset-frontend/src/explore/components/controls/index.ts
@@ -59,6 +59,7 @@ import NumberControl from './NumberControl';
import TimeRangeControl from './TimeRangeControl';
import ColorBreakpointsControl from './ColorBreakpointsControl';
import IntervalColorsControl from './IntervalColorsControl';
+import BulletRangeColorsControl from './BulletRangeColorsControl';
import MatrixifyDimensionControl from './MatrixifyDimensionControl';
import JSEditorControl from './JSEditorControl';
import SwitchControl from './SwitchControl';
@@ -89,6 +90,7 @@ const controlMap = {
FixedOrMetricControl,
ColorBreakpointsControl,
IntervalColorsControl,
+ BulletRangeColorsControl,
HiddenControl,
JSEditorControl,
LayerConfigsControl,
(superset) 01/04: feat(gauge): replace scheme-index interval colors with a color picker
Posted by ru...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch feat/color-picker-consolidation
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 063779e9b2360996a98d607c1a8af7176328174b
Author: Claude Code <no...@anthropic.com>
AuthorDate: Fri Aug 7 23:32:35 2026 -0700
feat(gauge): replace scheme-index interval colors with a color picker
The Gauge chart's "Interval colors" control asked users to enter
comma-separated 1-indexed positions into the chosen color scheme (e.g.
"1,2,4"), forcing them to count swatches by hand with no visual
feedback and silently discarding malformed input.
Replace it with IntervalColorsControl, a new control that renders one
ColorPickerControl per interval bound (parsed from the existing
`intervals` control) and stores real hex colors in a new
`interval_colors` form-data field, positionally matched to those
bounds.
Backward compatibility: charts saved before this control existed only
have `interval_color_indices` (the old scheme-index strings).
`Gauge/transformProps.ts#getIntervalBoundsAndColors` still resolves
those indices against the chart's categorical scheme at render time
whenever `interval_colors` is absent or empty, so existing dashboards
render identically without a data migration. The new control also
resolves legacy indices to real colors for display the first time such
a chart's control panel is opened, purely as an editor convenience.
Design note: bounds stay owned by the existing `intervals` text
control rather than being folded into the new control's row list, so
there's a single source of truth for bounds and no risk of the two
controls drifting out of sync.
---
.../src/Gauge/controlPanel.tsx | 16 +-
.../src/Gauge/transformProps.ts | 35 ++++-
.../plugin-chart-echarts/src/Gauge/types.ts | 15 ++
.../test/Gauge/transformProps.test.ts | 163 ++++++++++++++++++---
.../IntervalColorsControl.test.tsx | 142 ++++++++++++++++++
.../controls/IntervalColorsControl/index.tsx | 142 ++++++++++++++++++
.../controls/IntervalColorsControl/types.ts | 44 ++++++
.../src/explore/components/controls/index.ts | 2 +
8 files changed, 533 insertions(+), 26 deletions(-)
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx
index 423fa6f4d81..308579dd9af 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/controlPanel.tsx
@@ -20,6 +20,7 @@ import { t } from '@apache-superset/core/translation';
import {
sharedControls,
ControlPanelConfig,
+ ControlPanelState,
ControlSubSectionHeader,
D3_FORMAT_OPTIONS,
getStandardizedControls,
@@ -278,15 +279,22 @@ const config: ControlPanelConfig = {
],
[
{
- name: 'interval_color_indices',
+ name: 'interval_colors',
config: {
- type: 'TextControl',
+ type: 'IntervalColorsControl',
label: t('Interval colors'),
description: t(
- 'Comma-separated color picks for the intervals, e.g. 1,2,4. Integers denote colors from the chosen color scheme and are 1-indexed. Length must be matching that of interval bounds.',
+ 'Pick a color for each interval band defined above by its upper bound. Charts saved with the legacy 1-indexed "Interval colors" text field are automatically resolved against the chosen color scheme the first time this panel is opened.',
),
renderTrigger: true,
- default: DEFAULT_FORM_DATA.intervalColorIndices,
+ default: DEFAULT_FORM_DATA.intervalColors,
+ shouldMapStateToProps: () => true,
+ mapStateToProps: (state: ControlPanelState) => ({
+ intervals: state?.controls?.intervals?.value as string,
+ legacyIntervalColorIndices: state?.controls
+ ?.interval_color_indices?.value as string,
+ colorScheme: state?.controls?.color_scheme?.value as string,
+ }),
},
},
],
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
index dceb4927d02..57181b39340 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/transformProps.ts
@@ -53,29 +53,52 @@ import { getColtypesMapping } from '../utils/series';
export const getIntervalBoundsAndColors = (
intervals: string,
intervalColorIndices: string,
+ intervalColors: string[] | undefined,
colorFn: CategoricalColorScale,
min: number,
max: number,
): Array<[number, string]> => {
let intervalBoundsNonNormalized;
- let intervalColorIndicesArray;
try {
intervalBoundsNonNormalized = parseNumbersList(intervals, ',');
- intervalColorIndicesArray = parseNumbersList(intervalColorIndices, ',');
} catch (error) {
intervalBoundsNonNormalized = [] as number[];
- intervalColorIndicesArray = [] as number[];
}
const intervalBounds = intervalBoundsNonNormalized.map(
bound => (bound - min) / (max - min),
);
- const intervalColors = intervalColorIndicesArray.map(
+
+ // New-style: `interval_colors` holds real hex/rgb colors chosen through
+ // the Gauge control panel's per-interval `IntervalColorsControl`,
+ // positionally matched to the bounds parsed from `intervals`. Prefer this
+ // whenever it's populated.
+ if (Array.isArray(intervalColors) && intervalColors.length > 0) {
+ return intervalBounds.map((val, idx) => [
+ val,
+ intervalColors[idx] || colorFn.colors[idx],
+ ]);
+ }
+
+ // Backward compatibility: charts saved before `interval_colors` existed
+ // store `interval_color_indices`, a comma-separated list of 1-indexed
+ // positions into the chart's categorical color scheme (e.g. "1,2,4")
+ // instead of literal colors. Resolve those indices against the scheme
+ // here -- exactly as this function always has -- so existing dashboards
+ // keep rendering identically. No data migration is required: this
+ // fallback runs every time such a chart is rendered.
+ let intervalColorIndicesArray;
+ try {
+ intervalColorIndicesArray = parseNumbersList(intervalColorIndices, ',');
+ } catch (error) {
+ intervalColorIndicesArray = [] as number[];
+ }
+ const legacyColors = intervalColorIndicesArray.map(
ind => colorFn.colors[(ind - 1) % colorFn.colors.length],
);
return intervalBounds.map((val, idx) => {
- const color = intervalColors[idx];
+ const color = legacyColors[idx];
return [val, color || colorFn.colors[idx]];
});
};
@@ -135,6 +158,7 @@ export default function transformProps(
showPointer,
intervals,
intervalColorIndices,
+ intervalColors,
valueFormatter,
sliceId,
}: EchartsGaugeFormData = { ...DEFAULT_GAUGE_FORM_DATA, ...formData };
@@ -249,6 +273,7 @@ export default function transformProps(
const intervalBoundsAndColors = getIntervalBoundsAndColors(
intervals,
intervalColorIndices,
+ intervalColors,
colorFn,
min,
max,
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/types.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/types.ts
index 6f1f971d70a..7ea1c1a1b82 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/types.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Gauge/types.ts
@@ -50,7 +50,21 @@ export type EchartsGaugeFormData = QueryFormData & {
endAngle: number;
showPointer: boolean;
intervals: string;
+ /**
+ * @deprecated Legacy 1-indexed positions into `colorScheme`, e.g. "1,2,4".
+ * Superset versions before `intervalColors` existed stored interval colors
+ * this way. Still read at render time (see
+ * `transformProps.ts#getIntervalBoundsAndColors`) so charts saved with
+ * this shape keep rendering identically without a migration.
+ */
intervalColorIndices: string;
+ /**
+ * Real hex/rgb colors for each interval band, positionally matched to the
+ * bounds parsed from `intervals`. Authored via the `IntervalColorsControl`
+ * control panel row. Takes precedence over `intervalColorIndices` when
+ * present.
+ */
+ intervalColors?: string[];
valueFormatter: string;
};
@@ -74,6 +88,7 @@ export const DEFAULT_FORM_DATA: Partial<EchartsGaugeFormData> = {
showPointer: true,
intervals: '',
intervalColorIndices: '',
+ intervalColors: [],
valueFormatter: '{value}',
};
diff --git a/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/transformProps.test.ts
index b8fd46d0527..99e58887685 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/test/Gauge/transformProps.test.ts
@@ -279,6 +279,82 @@ describe('Echarts Gauge transformProps', () => {
expect(seriesData[1].name).toBe('year: 2008, platform: PC');
expect(seriesData[1].itemStyle.color).toBe('#ff7f0e');
});
+
+ test('should use interval_colors (real hex values) instead of legacy interval_color_indices when present', () => {
+ const formData: SqlaFormData = {
+ ...baseFormData,
+ groupby: ['year', 'platform'],
+ intervals: '60,100',
+ // Legacy field is intentionally still set to verify the new field
+ // takes precedence rather than requiring the old one to be cleared.
+ intervalColorIndices: '1,2',
+ intervalColors: ['#ff0000', '#00ff00'],
+ minVal: 20,
+ };
+ const queriesData = [
+ {
+ colnames: ['year', 'platform', 'count'],
+ data: [
+ { year: 2011, platform: 'PC', count: 140 },
+ { year: 2008, platform: 'PC', count: 76 },
+ ],
+ },
+ ];
+
+ const chartProps = new ChartProps({
+ formData,
+ width: 800,
+ height: 600,
+ queriesData,
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(chartProps as EchartsGaugeChartProps);
+ const { axisLine } = (result.echartOptions as any).series[0];
+
+ expect(axisLine.lineStyle.color).toEqual([
+ [0.5, '#ff0000'],
+ [1, '#00ff00'],
+ ]);
+ });
+
+ test('a chart saved before interval_colors existed still renders using legacy interval_color_indices', () => {
+ // Simulates form_data persisted by a Gauge chart saved before this
+ // feature: only the legacy fields are present, `intervalColors` is
+ // absent entirely (not just empty).
+ const formData: SqlaFormData = {
+ ...baseFormData,
+ groupby: ['year', 'platform'],
+ intervals: '60,100',
+ intervalColorIndices: '1,2',
+ minVal: 20,
+ };
+ const queriesData = [
+ {
+ colnames: ['year', 'platform', 'count'],
+ data: [
+ { year: 2011, platform: 'PC', count: 140 },
+ { year: 2008, platform: 'PC', count: 76 },
+ ],
+ },
+ ];
+
+ const chartProps = new ChartProps({
+ formData,
+ width: 800,
+ height: 600,
+ queriesData,
+ theme: supersetTheme,
+ });
+
+ const result = transformProps(chartProps as EchartsGaugeChartProps);
+ const { axisLine } = (result.echartOptions as any).series[0];
+
+ expect(axisLine.lineStyle.color).toEqual([
+ [0.5, '#1f77b4'],
+ [1, '#ff7f0e'],
+ ]);
+ });
});
describe('Min/Max calculation and axis labels', () => {
@@ -687,41 +763,94 @@ describe('Min/Max calculation and axis labels', () => {
});
describe('getIntervalBoundsAndColors', () => {
- test('should generate correct interval bounds and colors', () => {
+ test('should generate correct interval bounds and colors from legacy indices', () => {
const colorFn = CategoricalColorNamespace.getScale(
'supersetColors' as string,
);
- expect(getIntervalBoundsAndColors('', '', colorFn, 0, 10)).toEqual([]);
- expect(getIntervalBoundsAndColors('4, 10', '1, 2', colorFn, 0, 10)).toEqual(
- [
- [0.4, '#1f77b4'],
- [1, '#ff7f0e'],
- ],
- );
expect(
- getIntervalBoundsAndColors('4, 8, 10', '9, 8, 7', colorFn, 0, 10),
+ getIntervalBoundsAndColors('', '', undefined, colorFn, 0, 10),
+ ).toEqual([]);
+ expect(
+ getIntervalBoundsAndColors('4, 10', '1, 2', undefined, colorFn, 0, 10),
+ ).toEqual([
+ [0.4, '#1f77b4'],
+ [1, '#ff7f0e'],
+ ]);
+ expect(
+ getIntervalBoundsAndColors(
+ '4, 8, 10',
+ '9, 8, 7',
+ undefined,
+ colorFn,
+ 0,
+ 10,
+ ),
).toEqual([
[0.4, '#bcbd22'],
[0.8, '#7f7f7f'],
[1, '#e377c2'],
]);
- expect(getIntervalBoundsAndColors('4, 10', '1, 2', colorFn, 2, 10)).toEqual(
- [
- [0.25, '#1f77b4'],
- [1, '#ff7f0e'],
- ],
- );
expect(
- getIntervalBoundsAndColors('-4, 0', '1, 2', colorFn, -10, 0),
+ getIntervalBoundsAndColors('4, 10', '1, 2', undefined, colorFn, 2, 10),
+ ).toEqual([
+ [0.25, '#1f77b4'],
+ [1, '#ff7f0e'],
+ ]);
+ expect(
+ getIntervalBoundsAndColors('-4, 0', '1, 2', undefined, colorFn, -10, 0),
).toEqual([
[0.6, '#1f77b4'],
[1, '#ff7f0e'],
]);
expect(
- getIntervalBoundsAndColors('-4, -2', '1, 2', colorFn, -10, -2),
+ getIntervalBoundsAndColors('-4, -2', '1, 2', undefined, colorFn, -10, -2),
).toEqual([
[0.75, '#1f77b4'],
[1, '#ff7f0e'],
]);
});
+
+ test('should prefer interval_colors (real hex values) over legacy indices when present', () => {
+ const colorFn = CategoricalColorNamespace.getScale(
+ 'supersetColors' as string,
+ );
+ expect(
+ getIntervalBoundsAndColors(
+ '4, 10',
+ '1, 2',
+ ['#ff0000', '#00ff00'],
+ colorFn,
+ 0,
+ 10,
+ ),
+ ).toEqual([
+ [0.4, '#ff0000'],
+ [1, '#00ff00'],
+ ]);
+ });
+
+ test('should fall back to the color scheme for bounds missing an explicit interval_colors entry', () => {
+ const colorFn = CategoricalColorNamespace.getScale(
+ 'supersetColors' as string,
+ );
+ expect(
+ getIntervalBoundsAndColors('4, 8, 10', '', ['#ff0000'], colorFn, 0, 10),
+ ).toEqual([
+ [0.4, '#ff0000'],
+ [0.8, colorFn.colors[1]],
+ [1, colorFn.colors[2]],
+ ]);
+ });
+
+ test('an empty interval_colors array falls back to legacy indices', () => {
+ const colorFn = CategoricalColorNamespace.getScale(
+ 'supersetColors' as string,
+ );
+ expect(
+ getIntervalBoundsAndColors('4, 10', '1, 2', [], colorFn, 0, 10),
+ ).toEqual([
+ [0.4, '#1f77b4'],
+ [1, '#ff7f0e'],
+ ]);
+ });
});
diff --git a/superset-frontend/src/explore/components/controls/IntervalColorsControl/IntervalColorsControl.test.tsx b/superset-frontend/src/explore/components/controls/IntervalColorsControl/IntervalColorsControl.test.tsx
new file mode 100644
index 00000000000..d801e869b26
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/IntervalColorsControl/IntervalColorsControl.test.tsx
@@ -0,0 +1,142 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
+import {
+ CategoricalScheme,
+ getCategoricalSchemeRegistry,
+} from '@superset-ui/core';
+import IntervalColorsControl from 'src/explore/components/controls/IntervalColorsControl';
+
+beforeAll(() => {
+ getCategoricalSchemeRegistry().registerValue(
+ 'testScheme',
+ new CategoricalScheme({
+ id: 'testScheme',
+ colors: ['#1f77b4', '#ff7f0e', '#2ca02c'],
+ }),
+ );
+});
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+test('renders a hint and no rows when no interval bounds are configured', () => {
+ render(<IntervalColorsControl onChange={jest.fn()} />);
+
+ expect(
+ screen.getByText('Add interval bounds above to configure colors here.'),
+ ).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 0,
+ );
+});
+
+test('renders one color picker row per parsed interval bound', () => {
+ render(
+ <IntervalColorsControl
+ onChange={jest.fn()}
+ intervals="20,60,100"
+ colorScheme="testScheme"
+ />,
+ );
+
+ expect(screen.getByText(/Up to 20/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 60/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 100/)).toBeInTheDocument();
+ expect(document.querySelectorAll('.ant-color-picker-trigger')).toHaveLength(
+ 3,
+ );
+});
+
+test('falls back to the categorical scheme when there is no explicit value or legacy data', () => {
+ render(
+ <IntervalColorsControl
+ onChange={jest.fn()}
+ intervals="20,60"
+ colorScheme="testScheme"
+ />,
+ );
+
+ expect(screen.getByText('#1F77B4')).toBeInTheDocument();
+ expect(screen.getByText('#FF7F0E')).toBeInTheDocument();
+});
+
+test('resolves legacy interval_color_indices against the color scheme for display', () => {
+ render(
+ <IntervalColorsControl
+ onChange={jest.fn()}
+ intervals="20,60"
+ legacyIntervalColorIndices="2,3"
+ colorScheme="testScheme"
+ />,
+ );
+
+ // 1-indexed: index 2 -> '#ff7f0e', index 3 -> '#2ca02c'
+ expect(screen.getByText('#FF7F0E')).toBeInTheDocument();
+ expect(screen.getByText('#2CA02C')).toBeInTheDocument();
+});
+
+test('explicit value takes precedence over legacy indices', () => {
+ render(
+ <IntervalColorsControl
+ onChange={jest.fn()}
+ intervals="20,60"
+ value={['#ff0000', '#00ff00']}
+ legacyIntervalColorIndices="2,3"
+ colorScheme="testScheme"
+ />,
+ );
+
+ expect(screen.getByText('#FF0000')).toBeInTheDocument();
+ expect(screen.getByText('#00FF00')).toBeInTheDocument();
+});
+
+test('calls onChange with the full color array when a row color is picked', async () => {
+ const onChange = jest.fn();
+ render(
+ <IntervalColorsControl
+ onChange={onChange}
+ intervals="20,60"
+ value={['#ff0000', '#00ff00']}
+ colorScheme="testScheme"
+ />,
+ );
+
+ const triggers = document.querySelectorAll('.ant-color-picker-trigger');
+ expect(triggers).toHaveLength(2);
+
+ await userEvent.click(triggers[1]);
+
+ await waitFor(() => {
+ expect(
+ document.querySelector('.ant-color-picker-presets-color'),
+ ).toBeInTheDocument();
+ });
+
+ const presets = document.querySelectorAll('.ant-color-picker-presets-color');
+ await userEvent.click(presets[0]);
+
+ expect(onChange).toHaveBeenCalledWith(['#ff0000', '#1f77b4']);
+});
diff --git a/superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx b/superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx
new file mode 100644
index 00000000000..92d7c0f361b
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/IntervalColorsControl/index.tsx
@@ -0,0 +1,142 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { styled } from '@apache-superset/core/theme';
+import { getCategoricalSchemeRegistry } from '@superset-ui/core';
+import ControlHeader from '../../ControlHeader';
+import ColorPickerControl from '../ColorPickerControl';
+import type { ColorPickerValue } from '../ColorPickerControl';
+import { IntervalColorsControlProps } from './types';
+
+const IntervalRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: ${({ theme }) => theme.sizeUnit * 2}px;
+ margin-bottom: ${({ theme }) => theme.sizeUnit}px;
+`;
+
+const BoundLabel = styled.span`
+ min-width: 90px;
+ color: ${({ theme }) => theme.colorTextSecondary};
+ font-size: ${({ theme }) => theme.fontSizeSM}px;
+`;
+
+const parseBounds = (intervals?: string): number[] =>
+ (intervals ?? '')
+ .split(',')
+ .map(part => part.trim())
+ .filter(part => part !== '')
+ .map(Number)
+ .filter(bound => Number.isFinite(bound));
+
+/**
+ * Resolves the legacy `interval_color_indices` control (comma-separated,
+ * 1-indexed positions into the chosen categorical color scheme) into real
+ * hex colors, positionally matched to `bounds`. This exists purely so the
+ * control panel shows sensible colors the first time an admin opens a Gauge
+ * chart that was saved before `interval_colors` existed -- it doesn't
+ * persist anything on its own. Chart rendering for charts that are *never*
+ * reopened for editing is handled independently by the equivalent fallback
+ * in `Gauge/transformProps.ts`'s `getIntervalBoundsAndColors`.
+ */
+const resolveLegacyColors = (
+ bounds: number[],
+ legacyIntervalColorIndices: string | undefined,
+ colorScheme: string | undefined,
+): string[] => {
+ const schemeColors =
+ getCategoricalSchemeRegistry().get(colorScheme)?.colors ?? [];
+ const indices = (legacyIntervalColorIndices ?? '')
+ .split(',')
+ .map(part => part.trim())
+ .map(part => (part === '' ? NaN : Number(part)));
+ return bounds.map((_, index) => {
+ const legacyIndex = indices[index];
+ if (schemeColors.length === 0) return '';
+ if (Number.isFinite(legacyIndex)) {
+ return schemeColors[
+ (((legacyIndex - 1) % schemeColors.length) + schemeColors.length) %
+ schemeColors.length
+ ];
+ }
+ return schemeColors[index % schemeColors.length];
+ });
+};
+
+/**
+ * Per-interval color editor for the Gauge chart. Row *count* is driven by
+ * the sibling `intervals` control (one row per parsed upper bound) so bound
+ * values keep a single source of truth; this control only owns colors,
+ * stored as an array of hex strings positionally matched to those bounds.
+ */
+export default function IntervalColorsControl({
+ value,
+ onChange,
+ intervals,
+ legacyIntervalColorIndices,
+ colorScheme,
+ ...headerProps
+}: IntervalColorsControlProps) {
+ const bounds = parseBounds(intervals);
+ const legacyColors = resolveLegacyColors(
+ bounds,
+ legacyIntervalColorIndices,
+ colorScheme,
+ );
+ const schemeColors =
+ getCategoricalSchemeRegistry().get(colorScheme)?.colors ?? [];
+
+ const colorAt = (index: number): string =>
+ value?.[index] ||
+ legacyColors[index] ||
+ schemeColors[index % (schemeColors.length || 1)] ||
+ '';
+
+ const handleColorChange = (index: number) => (color: ColorPickerValue) => {
+ if (typeof color !== 'string') return;
+ const next = bounds.map((_, i) => (i === index ? color : colorAt(i)));
+ onChange?.(next);
+ };
+
+ return (
+ <div>
+ <ControlHeader {...headerProps} />
+ {bounds.length === 0 ? (
+ <BoundLabel>
+ {t('Add interval bounds above to configure colors here.')}
+ </BoundLabel>
+ ) : (
+ bounds.map((bound, index) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <IntervalRow key={index}>
+ <BoundLabel>
+ {t('Up to')} {bound}
+ </BoundLabel>
+ <ColorPickerControl
+ ariaLabel={t('Color for interval up to %s', bound)}
+ value={colorAt(index)}
+ onChange={handleColorChange(index)}
+ outputFormat="hex"
+ />
+ </IntervalRow>
+ ))
+ )}
+ </div>
+ );
+}
diff --git a/superset-frontend/src/explore/components/controls/IntervalColorsControl/types.ts b/superset-frontend/src/explore/components/controls/IntervalColorsControl/types.ts
new file mode 100644
index 00000000000..9252c60fb42
--- /dev/null
+++ b/superset-frontend/src/explore/components/controls/IntervalColorsControl/types.ts
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+export interface IntervalColorsControlProps {
+ value?: string[];
+ onChange?: (value: string[]) => void;
+ label?: string;
+ description?: string;
+ hovered?: boolean;
+ renderTrigger?: boolean;
+ warning?: string;
+ /**
+ * Live value of the sibling `intervals` control (comma-separated upper
+ * bounds), supplied via `mapStateToProps`. Drives how many color rows are
+ * rendered -- one per parsed bound -- so bounds stay authored in a single
+ * place (the existing `intervals` text control).
+ */
+ intervals?: string;
+ /**
+ * Legacy `interval_color_indices` value (comma-separated 1-indexed
+ * positions into the categorical color scheme), supplied via
+ * `mapStateToProps`. Used only to seed real colors for charts saved before
+ * this control existed; see `resolveLegacyColors` in index.tsx.
+ */
+ legacyIntervalColorIndices?: string;
+ /** Current categorical color scheme, used to resolve legacy indices and to
+ * pick sensible defaults for new rows. */
+ colorScheme?: string;
+}
diff --git a/superset-frontend/src/explore/components/controls/index.ts b/superset-frontend/src/explore/components/controls/index.ts
index 1550df945e7..69e8942cdc2 100644
--- a/superset-frontend/src/explore/components/controls/index.ts
+++ b/superset-frontend/src/explore/components/controls/index.ts
@@ -58,6 +58,7 @@ import ZoomConfigControl from './ZoomConfigControl/ZoomConfigControl';
import NumberControl from './NumberControl';
import TimeRangeControl from './TimeRangeControl';
import ColorBreakpointsControl from './ColorBreakpointsControl';
+import IntervalColorsControl from './IntervalColorsControl';
import MatrixifyDimensionControl from './MatrixifyDimensionControl';
import JSEditorControl from './JSEditorControl';
import SwitchControl from './SwitchControl';
@@ -87,6 +88,7 @@ const controlMap = {
DndColumnMetricSelect,
FixedOrMetricControl,
ColorBreakpointsControl,
+ IntervalColorsControl,
HiddenControl,
JSEditorControl,
LayerConfigsControl,