Skip to content

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

Apply embedding theme colors to hand-picked chart series (#81014)

Sébastien69256a104a3e
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjs
index 812b4f95c52..aff805bda58 100644
--- a/frontend/lint/module-boundaries.mjs
+++ b/frontend/lint/module-boundaries.mjs
@@ -383,6 +383,7 @@ const elements = [
// GraalJS) - like app.tsx, it composes OSS + EE code for a build artifact.
// Full-mode entries match before folder patterns, whatever the order.
"frontend/src/metabase/static-viz/index.tsx",
+ "frontend/src/metabase/static-viz/index.unit.spec.tsx",
].map((path) =>
createElement({
type: "app",
diff --git a/frontend/src/embedding-sdk-bundle/lib/theme/embedding-color-palette.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/theme/embedding-color-palette.unit.spec.ts
index a612bd87314..b7603048cd6 100644
--- a/frontend/src/embedding-sdk-bundle/lib/theme/embedding-color-palette.unit.spec.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/theme/embedding-color-palette.unit.spec.ts
@@ -1,4 +1,10 @@
-import { getEmbeddingColorPalette } from "metabase/embedding-sdk/theme/embedding-color-palette";
+import {
+ getEmbeddingColorPalette,
+ setGlobalEmbeddingColors,
+} from "metabase/embedding-sdk/theme/embedding-color-palette";
+import { colors } from "metabase/ui/colors";
+import { getSeriesColors } from "metabase/viz-core";
+import type { SeriesSettings } from "metabase-types/api";
describe("Embedding Color Palette", () => {
it("transforms chart color overrides into accent colors", () => {
@@ -25,4 +31,41 @@ describe("Embedding Color Palette", () => {
expect(palette[key]).toBe(expected[key]);
}
});
+
+ describe("chart series colors", () => {
+ const THEME_CHARTS = ["#111111", "#222222", "#333333"];
+
+ const getCountSeriesColor = (series: SeriesSettings) =>
+ getSeriesColors(["count"], { series_settings: { count: series } }, [
+ undefined,
+ ]).count;
+
+ afterEach(() => {
+ setGlobalEmbeddingColors();
+ });
+
+ it("follows the theme when the series records a palette color", () => {
+ setGlobalEmbeddingColors({ charts: THEME_CHARTS });
+
+ expect(
+ getCountSeriesColor({ color: "#123456", color_name: "accent2" }),
+ ).toBe(THEME_CHARTS[2]);
+ });
+
+ it("leaves a series that only has a stored color untouched", () => {
+ const pickedColor = colors.accent2;
+
+ setGlobalEmbeddingColors({ charts: THEME_CHARTS });
+
+ expect(getCountSeriesColor({ color: pickedColor })).toBe(pickedColor);
+ });
+
+ it("leaves a series alone when the theme sets no chart colors", () => {
+ setGlobalEmbeddingColors({ brand: "#123456" });
+
+ expect(
+ getCountSeriesColor({ color: "#123456", color_name: "accent2" }),
+ ).toBe(colors.accent2);
+ });
+ });
});
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 531a3cdbcee..1519fc35867 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -139,6 +139,8 @@ export type LineSize = "S" | "M" | "L";
export type SeriesSettings = {
title?: string;
color?: string;
+ /** Palette color the series was given, so it can follow the active palette */
+ color_name?: string;
show_series_values?: boolean;
display?: VisualizationDisplay;
axis?: string;
diff --git a/frontend/src/metabase-types/api/visualization-settings.ts b/frontend/src/metabase-types/api/visualization-settings.ts
index b1027a0e1ed..962f3062fc1 100644
--- a/frontend/src/metabase-types/api/visualization-settings.ts
+++ b/frontend/src/metabase-types/api/visualization-settings.ts
@@ -48,6 +48,8 @@ export interface PieRow {
name: string;
originalName: string;
color: string;
+ /** Palette color the slice was given, so it can follow the active palette */
+ color_name?: string;
defaultColor: boolean;
enabled: boolean;
hidden: boolean;
@@ -59,6 +61,8 @@ export interface TreemapRow {
name: string;
originalName: string;
color: string;
+ /** Palette color the group was given, so it can follow the active palette */
+ color_name?: string;
defaultColor: boolean;
enabled: boolean;
hidden: boolean;
diff --git a/frontend/src/metabase/common/components/ColorSelector/ColorSelector.tsx b/frontend/src/metabase/common/components/ColorSelector/ColorSelector.tsx
index b8e66dda13e..cf049cdb557 100644
--- a/frontend/src/metabase/common/components/ColorSelector/ColorSelector.tsx
+++ b/frontend/src/metabase/common/components/ColorSelector/ColorSelector.tsx
@@ -5,6 +5,7 @@ import type { PillSize } from "metabase/common/components/ColorPill";
import { ColorPill } from "metabase/common/components/ColorPill";
import { Center, Popover } from "metabase/ui";
+import type { ColorSelectorOption } from "./ColorSelectorPopover";
import { ColorSelectorPopover } from "./ColorSelectorPopover";
export type ColorSelectorAttributes = Omit<
@@ -14,9 +15,9 @@ export type ColorSelectorAttributes = Omit<
export interface ColorSelectorProps extends ColorSelectorAttributes {
value: string;
- colors: string[];
+ colors: ColorSelectorOption[];
pillSize?: PillSize;
- onChange?: (newValue: string) => void;
+ onChange?: (hexValue: string, colorName?: string) => void;
withinPortal?: boolean;
}
diff --git a/frontend/src/metabase/common/components/ColorSelector/ColorSelector.unit.spec.tsx b/frontend/src/metabase/common/components/ColorSelector/ColorSelector.unit.spec.tsx
index 6f2f200b54a..96c9b1bf909 100644
--- a/frontend/src/metabase/common/components/ColorSelector/ColorSelector.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/ColorSelector/ColorSelector.unit.spec.tsx
@@ -4,6 +4,12 @@ import { render, screen, within } from "__support__/ui";
import { ColorSelector } from "./ColorSelector";
+const pickColor = async (label: string) => {
+ await userEvent.click(screen.getByLabelText("white"));
+ const tooltip = await screen.findByRole("dialog");
+ await userEvent.click(within(tooltip).getByLabelText(label));
+};
+
describe("ColorSelector", () => {
it("should select a color in a popover", async () => {
const onChange = jest.fn();
@@ -16,10 +22,27 @@ describe("ColorSelector", () => {
/>,
);
- await userEvent.click(screen.getByLabelText("white"));
- const tooltip = await screen.findByRole("dialog");
- await userEvent.click(within(tooltip).getByLabelText("blue"));
+ await pickColor("blue");
+
+ expect(onChange).toHaveBeenCalledWith("blue", undefined);
+ });
+
+ it("should report the palette name of the color that was picked", async () => {
+ const onChange = jest.fn();
+
+ render(
+ <ColorSelector
+ value="white"
+ colors={[
+ { name: "accent0", value: "blue" },
+ { name: "accent1", value: "green" },
+ ]}
+ onChange={onChange}
+ />,
+ );
+
+ await pickColor("green");
- expect(onChange).toHaveBeenCalledWith("blue");
+ expect(onChange).toHaveBeenCalledWith("green", "accent1");
});
});
diff --git a/frontend/src/metabase/common/components/ColorSelector/ColorSelectorPopover.tsx b/frontend/src/metabase/common/components/ColorSelector/ColorSelectorPopover.tsx
index 2ad63ddad50..6aa7d6279c1 100644
--- a/frontend/src/metabase/common/components/ColorSelector/ColorSelectorPopover.tsx
+++ b/frontend/src/metabase/common/components/ColorSelector/ColorSelectorPopover.tsx
@@ -5,13 +5,29 @@ import { ColorPill } from "metabase/common/components/ColorPill";
import { PopoverRoot } from "./ColorSelectorPopover.styled";
+/**
+ * A picker given named palette colors reports which one was chosen, so the
+ * choice can be stored as a reference to the palette rather than a fixed value.
+ * The name is opaque here; callers that care what it refers to (e.g. an
+ * accent color key) narrow it on their end.
+ */
+export type ColorSelectorOption = string | { name: string; value: string };
+
+type NormalizedOption = {
+ name?: string;
+ value: string;
+};
+
+const toNamedColor = (option: ColorSelectorOption): NormalizedOption =>
+ typeof option === "string" ? { value: option } : option;
+
export interface ColorSelectorPopoverProps extends Omit<
HTMLAttributes<HTMLDivElement>,
"onChange"
> {
value?: string;
- colors: string[];
- onChange?: (newValue: string) => void;
+ colors: ColorSelectorOption[];
+ onChange?: (hexValue: string, colorName?: string) => void;
onClose?: () => void;
}
@@ -20,8 +36,8 @@ export const ColorSelectorPopover = forwardRef(function ColorSelector(
ref: Ref<HTMLDivElement>,
) {
const handleSelect = useCallback(
- (newValue: string) => {
- onChange?.(newValue);
+ (hexValue: string, colorName?: string) => {
+ onChange?.(hexValue, colorName);
onClose?.();
},
[onChange, onClose],
@@ -29,12 +45,12 @@ export const ColorSelectorPopover = forwardRef(function ColorSelector(
return (
<PopoverRoot {...props} ref={ref}>
- {colors.map((option, index) => (
+ {colors.map(toNamedColor).map((option, index) => (
<ColorPill
key={index}
- color={option}
- isSelected={value === option}
- onSelect={handleSelect}
+ color={option.value}
+ isSelected={value === option.value}
+ onSelect={(newValue) => handleSelect(newValue, option.name)}
/>
))}
</PopoverRoot>
diff --git a/frontend/src/metabase/common/components/ColorSelector/index.ts b/frontend/src/metabase/common/components/ColorSelector/index.ts
index 7957052e9b8..14a3ef99bbe 100644
--- a/frontend/src/metabase/common/components/ColorSelector/index.ts
+++ b/frontend/src/metabase/common/components/ColorSelector/index.ts
@@ -1 +1,2 @@
export { ColorSelector } from "./ColorSelector";
+export type { ColorSelectorOption } from "./ColorSelectorPopover";
diff --git a/frontend/src/metabase/static-viz/index.tsx b/frontend/src/metabase/static-viz/index.tsx
index 1c2186048b3..e5a9b234674 100644
--- a/frontend/src/metabase/static-viz/index.tsx
+++ b/frontend/src/metabase/static-viz/index.tsx
@@ -13,6 +13,7 @@ import { LegacyStaticChart } from "metabase/static-viz/containers/LegacyStaticCh
import type { LegacyStaticChartType } from "metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart";
import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";
import { measureTextEChartsAdapter } from "metabase/static-viz/lib/text";
+import { mutateColors } from "metabase/ui/colors/colors";
import { updateStartOfWeek } from "metabase/utils/i18n";
import MetabaseSettings from "metabase/utils/settings";
import { DEFAULT_VISUALIZER_DISPLAY } from "metabase/visualizer/constants";
@@ -133,6 +134,10 @@ function RenderChart(
"application-colors" as SettingKey,
options.applicationColors,
);
+ // The app loads the instance's colors from the page bootstrap, which this
+ // context has no access to. Without them, a palette color looked up by name
+ // would resolve to the default value rather than the instance's.
+ mutateColors(options.applicationColors ?? {});
if (typeof enterpriseOverrides === "function") {
enterpriseOverrides();
diff --git a/frontend/src/metabase/static-viz/index.unit.spec.tsx b/frontend/src/metabase/static-viz/index.unit.spec.tsx
new file mode 100644
index 00000000000..425062905b5
--- /dev/null
+++ b/frontend/src/metabase/static-viz/index.unit.spec.tsx
@@ -0,0 +1,74 @@
+import type { Card, RawSeries } from "metabase-types/api";
+import { createMockCard } from "metabase-types/api/mocks/card";
+import {
+ createMockColumn,
+ createMockDatasetData,
+} from "metabase-types/api/mocks/dataset";
+import { createMockTokenFeatures } from "metabase-types/api/mocks/settings";
+
+import type { RenderChartOptions } from "./types";
+
+import { renderChart } from "./index";
+
+const INSTANCE_ACCENT_3 = "#ABCDEF";
+
+const makeRawSeries = (colorName?: string): RawSeries<Card> => [
+ {
+ card: createMockCard({
+ display: "bar",
+ visualization_settings: {
+ "graph.dimensions": ["Category"],
+ "graph.metrics": ["Amount"],
+ series_settings: {
+ Amount: { color: "#EF8C8C", color_name: colorName },
+ },
+ },
+ }),
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "Category",
+ display_name: "Category",
+ base_type: "type/Text",
+ }),
+ createMockColumn({
+ name: "Amount",
+ display_name: "Amount",
+ base_type: "type/Integer",
+ semantic_type: "type/Number",
+ }),
+ ],
+ rows: [
+ ["Soy", 20],
+ ["Rye", 10],
+ ],
+ }),
+ },
+];
+
+const makeOptions = (): RenderChartOptions => ({
+ tokenFeatures: createMockTokenFeatures({ whitelabel: true }),
+ applicationColors: { accent3: INSTANCE_ACCENT_3 },
+ customFormatting: {},
+ startOfWeek: null,
+});
+
+const getChartSvg = (colorName?: string) =>
+ renderChart({
+ rawSeries: makeRawSeries(colorName),
+ dashcardSettings: {},
+ options: makeOptions(),
+ }).content;
+
+describe("static viz chart colors", () => {
+ it("paints a series recorded as a palette color with the instance's color", () => {
+ expect(getChartSvg("accent3")).toContain(INSTANCE_ACCENT_3);
+ });
+
+ it("keeps the stored color of a series with no recorded palette color", () => {
+ const svg = getChartSvg(undefined);
+
+ expect(svg).toContain("#EF8C8C");
+ expect(svg).not.toContain(INSTANCE_ACCENT_3);
+ });
+});
diff --git a/frontend/src/metabase/ui/colors/groups.ts b/frontend/src/metabase/ui/colors/groups.ts
index daa158868e2..a4bed37e9da 100644
--- a/frontend/src/metabase/ui/colors/groups.ts
+++ b/frontend/src/metabase/ui/colors/groups.ts
@@ -1,10 +1,15 @@
import Color from "color";
import _ from "underscore";
+import { ACCENT_COLOR_NAMES_MAP } from "./constants/accents";
import { ACCENT_COUNT, color } from "./palette";
-import type { AccentColorOptions, ColorName, ColorPalette } from "./types";
+import type { AccentColorOptions, ColorPalette, NamedColor } from "./types";
-export const getAccentColors = (
+/**
+ * Accent colors paired with their palette names, so that a picked color can be
+ * stored as a reference to the palette instead of a fixed value.
+ */
+export const getNamedAccentColors = (
{
main = true,
light = true,
@@ -13,63 +18,62 @@ export const getAccentColors = (
gray = true,
}: AccentColorOptions = {},
palette?: ColorPalette,
-): string[] => {
- const ranges: string[][] = [];
+): NamedColor[] => {
+ const ranges: NamedColor[][] = [];
if (main) {
- ranges.push(getMainAccentColors(palette, gray));
+ ranges.push(getNamedAccentVariant("base", palette, gray));
}
if (light) {
- ranges.push(getLightAccentColors(palette, gray));
+ ranges.push(getNamedAccentVariant("tint", palette, gray));
}
if (dark) {
- ranges.push(getDarkAccentColors(palette, gray));
+ ranges.push(getNamedAccentVariant("shade", palette, gray));
}
return harmony ? _.unzip(ranges).flat() : ranges.flat();
};
-const getBaseAccentsNames = (withGray = false) => {
- const accents: ColorName[] = _.times(
- ACCENT_COUNT,
- // Unjustified type cast. FIXME
- (i) => `accent${i}` as ColorName,
- );
- if (withGray) {
- accents.push("accent-gray");
- }
+export const getAccentColors = (
+ options: AccentColorOptions = {},
+ palette?: ColorPalette,
+): string[] => getNamedAccentColors(options, palette).map(({ value }) => value);
- return accents;
+// One variant (base/tint/shade) of the accent colors, as opposed to
+// getNamedAccentColors, which combines the variants an option set asks for.
+const getNamedAccentVariant = (
+ variant: "base" | "tint" | "shade",
+ palette?: ColorPalette,
+ withGray = false,
+): NamedColor[] => {
+ const accents = withGray
+ ? ACCENT_COLOR_NAMES_MAP
+ : ACCENT_COLOR_NAMES_MAP.slice(0, ACCENT_COUNT);
+
+ return accents.map((accent) => {
+ const name = accent[variant];
+
+ // Ensure that colors are defined in hex, not HSLA
+ return { name, value: Color(color(name, palette)).hex() };
+ });
};
export const getMainAccentColors = (
palette?: ColorPalette,
withGray = false,
-): string[] => {
- // Ensure that colors are defined in hex, not HSLA
- return getBaseAccentsNames(withGray).map((accent) =>
- Color(color(accent, palette)).hex(),
- );
-};
+): string[] =>
+ getAccentColors({ light: false, dark: false, gray: withGray }, palette);
export const getLightAccentColors = (
palette?: ColorPalette,
withGray = false,
-): string[] => {
- return getBaseAccentsNames(withGray).map((accent) =>
- // Unjustified type cast. FIXME
- Color(color(`${accent}-light` as ColorName, palette)).hex(),
- );
-};
+): string[] =>
+ getAccentColors({ main: false, dark: false, gray: withGray }, palette);
export const getDarkAccentColors = (
palette?: ColorPalette,
withGray = false,
-) => {
- return getBaseAccentsNames(withGray).map((accent) =>
- // Unjustified type cast. FIXME
- Color(color(`${accent}-dark` as ColorName, palette)).hex(),
- );
-};
+): string[] =>
+ getAccentColors({ main: false, light: false, gray: withGray }, palette);
export const getStatusColorRanges = (): string[][] => {
return [
diff --git a/frontend/src/metabase/ui/colors/groups.unit.spec.ts b/frontend/src/metabase/ui/colors/groups.unit.spec.ts
index 8d270a39d47..e94416d2d91 100644
--- a/frontend/src/metabase/ui/colors/groups.unit.spec.ts
+++ b/frontend/src/metabase/ui/colors/groups.unit.spec.ts
@@ -1,6 +1,6 @@
import Color from "color";
-import { getAccentColors } from "./groups";
+import { getAccentColors, getNamedAccentColors } from "./groups";
import { color } from "./palette";
describe("groups", () => {
@@ -19,4 +19,30 @@ describe("groups", () => {
expect(colors).toContain(Color(color("accent-gray-dark")).hex());
});
});
+
+ describe("getNamedAccentColors", () => {
+ it("should name every color the picker offers, in the same order", () => {
+ const named = getNamedAccentColors();
+
+ expect(named.map(({ value }) => value)).toEqual(getAccentColors());
+ });
+
+ it("should give each color the palette name it was read from", () => {
+ const named = getNamedAccentColors();
+
+ named.forEach(({ name, value }) => {
+ expect(value).toBe(Color(color(name)).hex());
+ });
+ });
+
+ it("should cover the base, light and dark variant of every accent", () => {
+ const names = getNamedAccentColors().map(({ name }) => name);
+
+ expect(names).toContain("accent0");
+ expect(names).toContain("accent0-light");
+ expect(names).toContain("accent0-dark");
+ expect(names).toContain("accent-gray");
+ expect(new Set(names).size).toBe(names.length);
+ });
+ });
});
diff --git a/frontend/src/metabase/ui/colors/types/accent-color-options.ts b/frontend/src/metabase/ui/colors/types/accent-color-options.ts
index b59fefd1c36..534fb1eab09 100644
--- a/frontend/src/metabase/ui/colors/types/accent-color-options.ts
+++ b/frontend/src/metabase/ui/colors/types/accent-color-options.ts
@@ -1,3 +1,5 @@
+import type { MetabaseAccentColorKey } from "./color-keys";
+
export interface AccentColorOptions {
main?: boolean;
light?: boolean;
@@ -5,3 +7,12 @@ export interface AccentColorOptions {
harmony?: boolean;
gray?: boolean;
}
+
+/**
+ * A palette color together with the name it is known by, so that a picked
+ * color can be stored as a reference to the palette rather than a fixed value.
+ */
+export interface NamedColor {
+ name: MetabaseAccentColorKey;
+ value: string;
+}
diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx
index 4a70f4e8db2..cdabcc27f80 100644
--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx
+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx
@@ -176,9 +176,11 @@ export const BaseChartSettings = ({
}, []);
const handleChangeSeriesColor = useCallback(
- (seriesKey: string, color: string) => {
+ (seriesKey: string, hexValue: string, colorName?: string) => {
if (chartSettings) {
- onChange?.(updateSeriesColor(chartSettings, seriesKey, color));
+ onChange?.(
+ updateSeriesColor(chartSettings, seriesKey, hexValue, colorName),
+ );
}
},
[chartSettings, onChange],
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesMultiple.tsx b/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesMultiple.tsx
index cacb0f3c3ca..cb9c8b86cf0 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesMultiple.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesMultiple.tsx
@@ -4,7 +4,7 @@ import { t } from "ttag";
import { ColorSelector } from "metabase/common/components/ColorSelector";
import CS from "metabase/css/core/index.css";
import { Flex } from "metabase/ui";
-import { getAccentColors } from "metabase/ui/colors/groups";
+import { getNamedAccentColors } from "metabase/ui/colors/groups";
import type { SingleSeries, VisualizationSettings } from "metabase-types/api";
import {
@@ -66,9 +66,12 @@ export const ChartNestedSettingSeriesMultiple = ({
<ColorSelector
withinPortal={false}
value={settings.color}
- colors={getAccentColors()}
- onChange={(value) =>
- onChangeObjectSettings(single, { color: value })
+ colors={getNamedAccentColors()}
+ onChange={(hexValue, colorName) =>
+ onChangeObjectSettings(single, {
+ color: hexValue,
+ color_name: colorName,
+ })
}
/>
<SeriesNameInput
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesSingle.tsx b/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesSingle.tsx
index d796ea8605b..5cd2f47cc9d 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesSingle.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartNestedSettingSeriesSingle.tsx
@@ -2,7 +2,7 @@ import cx from "classnames";
import { ColorSelector } from "metabase/common/components/ColorSelector";
import CS from "metabase/css/core/index.css";
-import { getAccentColors } from "metabase/ui/colors/groups";
+import { getNamedAccentColors } from "metabase/ui/colors/groups";
import type { SingleSeries, VisualizationSettings } from "metabase-types/api";
import { SeriesNameInput } from "./ChartNestedSettingSeries.styled";
@@ -42,8 +42,13 @@ const ChartNestedSettingsSeriesSingle = ({
<ColorSelector
withinPortal={false}
value={computedSettings.color}
- colors={getAccentColors()}
- onChange={(value) => onChangeObjectSettings(object, { color: value })}
+ colors={getNamedAccentColors()}
+ onChange={(hexValue, colorName) =>
+ onChangeObjectSettings(object, {
+ color: hexValue,
+ color_name: colorName,
+ })
+ }
/>
<SeriesNameInput
className={cx(CS.flexFull, CS.ml1, CS.alignSelfStretch)}
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingColorPicker/ChartSettingColorPicker.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingColorPicker/ChartSettingColorPicker.tsx
index 2cd51d42e3e..ac8f7fd4f1e 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingColorPicker/ChartSettingColorPicker.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingColorPicker/ChartSettingColorPicker.tsx
@@ -5,7 +5,7 @@ import { ColorSelector } from "metabase/common/components/ColorSelector";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { Box } from "metabase/ui";
-import { getAccentColors } from "metabase/ui/colors/groups";
+import { getNamedAccentColors } from "metabase/ui/colors/groups";
import type { AccentColorOptions } from "metabase/ui/colors/types";
interface ChartSettingColorPickerProps {
@@ -13,7 +13,7 @@ interface ChartSettingColorPickerProps {
value: string;
title?: string;
pillSize?: PillSize;
- onChange?: (newValue: string) => void;
+ onChange?: (hexValue: string, colorName?: string) => void;
accentColorOptions?: AccentColorOptions;
}
@@ -39,7 +39,7 @@ export const ChartSettingColorPicker = ({
<Box className={cx(CS.flex, CS.alignCenter, className)}>
<ColorSelector
value={value}
- colors={getAccentColors(accentColorOptions)}
+ colors={getNamedAccentColors(accentColorOptions)}
withinPortal={withinPortal}
onChange={onChange}
pillSize={pillSize}
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker/ChartSettingFieldPicker.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker/ChartSettingFieldPicker.tsx
index 21ed80efb70..800f5298cc4 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker/ChartSettingFieldPicker.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingFieldPicker/ChartSettingFieldPicker.tsx
@@ -36,7 +36,11 @@ type ChartSettingFieldPickerProps = {
dragHandleRef?: Ref<HTMLElement>;
fieldSettingWidget?: string | null;
onChange?: (value: string) => void;
- onChangeSeriesColor?: (seriesKey: string, value: string) => void;
+ onChangeSeriesColor?: (
+ seriesKey: string,
+ hexValue: string,
+ colorName?: string,
+ ) => void;
onRemove?: (() => void) | null;
onShowWidget?: (widget: MenuWidgetInfo, target: HTMLElement) => void;
options?: Array<{ name: string; value: string }>;
@@ -159,8 +163,8 @@ export const ChartSettingFieldPicker = ({
<ChartSettingColorPicker
pillSize="small"
value={colors[seriesKey]}
- onChange={(value) => {
- onChangeSeriesColor?.(seriesKey, value);
+ onChange={(hexValue, colorName) => {
+ onChangeSeriesColor?.(seriesKey, hexValue, colorName);
}}
className={CS.pointerEventsAll}
/>
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx
index 496daa93a71..25587934fa6 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedItems/ChartSettingOrderedItems.tsx
@@ -19,7 +19,7 @@ interface SortableColumnFunctions<T> {
onAdd?: (item: T) => void;
onEnable?: (item: T) => void;
getItemName: (item: T) => string;
- onColorChange?: (item: T, color: string) => void;
+ onColorChange?: (item: T, hexValue: string, colorName?: string) => void;
}
interface ChartSettingOrderedItemsProps<
T extends ChartSettingOrderedItem,
@@ -80,7 +80,8 @@ export function ChartSettingOrderedItems<T extends ChartSettingOrderedItem>({
}
onColorChange={
onColorChange
- ? (color: string) => onColorChange(item, color)
+ ? (hexValue: string, colorName?: string) =>
+ onColorChange(item, hexValue, colorName)
: undefined
}
color={getItemColor(item)}
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedSimple.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedSimple.tsx
index 66c4e3b0022..3d1c1821edb 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedSimple.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingOrderedSimple.tsx
@@ -33,7 +33,11 @@ interface ChartSettingOrderedSimpleProps {
) => void;
series: Series;
hasEditSettings: boolean;
- onChangeSeriesColor: (seriesKey: string, color: string) => void;
+ onChangeSeriesColor: (
+ seriesKey: string,
+ hexValue: string,
+ colorName?: string,
+ ) => void;
onSortEnd: (newItems: SortableItem[]) => void;
}
@@ -93,8 +97,8 @@ export const ChartSettingOrderedSimple = ({
);
const handleColorChange = useCallback(
- (item: SortableItem, color: string) => {
- onChangeSeriesColor(item.key, color);
+ (item: SortableItem, hexValue: string, colorName?: string) => {
+ onChangeSeriesColor(item.key, hexValue, colorName);
},
[onChangeSeriesColor],
);
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx
index 77d43a636fb..4571ed0f543 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSeriesOrder.tsx
@@ -8,7 +8,7 @@ import { ColorSelector } from "metabase/common/components/ColorSelector";
import type { DragEndEvent } from "metabase/common/components/Sortable";
import { Box, Button, Flex, Group, Icon, Select, Text } from "metabase/ui";
import { color } from "metabase/ui/colors";
-import { getAccentColors } from "metabase/ui/colors/groups";
+import { getNamedAccentColors } from "metabase/ui/colors/groups";
import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";
import { getEventTarget } from "metabase/utils/dom";
import { isEmpty } from "metabase/utils/validate";
@@ -117,8 +117,12 @@ export const ChartSettingSeriesOrder = ({
);
const handleColorChange = useCallback(
- (item: ChartSettingSeriesOrderItem, color: string) => {
- onChangeSeriesColor(item.key, color);
+ (
+ item: ChartSettingSeriesOrderItem,
+ hexValue: string,
+ colorName?: string,
+ ) => {
+ onChangeSeriesColor(item.key, hexValue, colorName);
},
[onChangeSeriesColor],
);
@@ -155,7 +159,7 @@ export const ChartSettingSeriesOrder = ({
<Group p={4} gap="sm">
<ColorSelector
value={otherColor ?? color("text-disabled")}
- colors={getAccentColors()}
+ colors={getNamedAccentColors()}
onChange={onOtherColorChange}
pillSize="small"
/>
diff --git a/frontend/src/metabase/visualizations/components/settings/ColumnItem/ColumnItem.tsx b/frontend/src/metabase/visualizations/components/settings/ColumnItem/ColumnItem.tsx
index cd6083c4b88..e1a13037f93 100644
--- a/frontend/src/metabase/visualizations/components/settings/ColumnItem/ColumnItem.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ColumnItem/ColumnItem.tsx
@@ -29,7 +29,7 @@ export interface ColumnItemProps {
onRemove?: (target: HTMLElement) => void;
onEdit?: (target: HTMLElement) => void;
onEnable?: (target: HTMLElement) => void;
- onColorChange?: (newColor: string) => void;
+ onColorChange?: (hexValue: string, colorName?: string) => void;
accentColorOptions?: AccentColorOptions;
onDragStart?: FlexProps["onDragStart"];
}
diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/PieRowsPicker.tsx b/frontend/src/metabase/visualizations/visualizations/PieChart/PieRowsPicker.tsx
index 36a9f92696b..947d239ae98 100644
--- a/frontend/src/metabase/visualizations/visualizations/PieChart/PieRowsPicker.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/PieRowsPicker.tsx
@@ -7,6 +7,7 @@ import {
type ComputedVisualizationSettings,
createHexToAccentNumberMap,
getPickerColorAlias,
+ withColorName,
} from "metabase/viz-core";
import type { PieRow, RawSeries } from "metabase-types/api";
@@ -45,13 +46,20 @@ export function PieRowsPicker({
return color(getPickerColorAlias(accentKey));
};
- const onChangeSeriesColor = (sliceKey: string, color: string) =>
+ const onChangeSeriesColor = (
+ sliceKey: string,
+ hexValue: string,
+ colorName?: string,
+ ) =>
onChangeSettings({
"pie.rows": pieRows.map((row) => {
if (row.key !== sliceKey) {
return row;
}
- return { ...row, color, defaultColor: false };
+ return withColorName(
+ { ...row, color: hexValue, defaultColor: false },
+ colorName,
+ );
}),
});
diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx
index 5216d7ffd66..230fde0ada0 100644
--- a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapGroupsPicker.tsx
@@ -4,6 +4,7 @@ import { ChartSettingSeriesOrder } from "metabase/visualizations/components/sett
import {
type TreemapGroupsPickerProps,
getTreemapChartColumns,
+ withColorName,
} from "metabase/viz-core";
import type { TreemapRow } from "metabase-types/api";
@@ -23,13 +24,20 @@ export function TreemapGroupsPicker({
getTreemapChartColumns(rawSeries[0]?.data?.cols ?? [], settings)
?.subGrouping != null;
- const handleChangeSeriesColor = (groupKey: string, color: string) =>
+ const handleChangeSeriesColor = (
+ groupKey: string,
+ hexValue: string,
+ colorName?: string,
+ ) =>
onChangeSettings({
"treemap.rows": treemapRows.map((row) => {
if (row.key !== groupKey) {
return row;
}
- return { ...row, color, defaultColor: false };
+ return withColorName(
+ { ...row, color: hexValue, defaultColor: false },
+ colorName,
+ );
}),
});
diff --git a/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.ts b/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.ts
index 53741d2ebdc..29065c1601a 100644
--- a/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.ts
+++ b/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.ts
@@ -3,6 +3,8 @@ import Color from "color";
import { getColorsForValues } from "metabase/ui/colors/charts";
import type { TreemapRow } from "metabase-types/api";
+import { getChartColor } from "../../../../lib/color-name";
+
import { getTreemapNodeKey } from "./data";
import type { TreemapTree } from "./types";
@@ -15,7 +17,7 @@ export function getTreemapColors(
): Record<string, string> {
const colors = getColorsForValues(tree.map(getTreemapNodeKey));
treemapRows?.forEach((row) => {
- colors[row.key] = row.color;
+ colors[row.key] = getChartColor(row.color, row.color_name);
});
return colors;
}
diff --git a/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.unit.spec.ts
new file mode 100644
index 00000000000..642e05bad95
--- /dev/null
+++ b/frontend/src/metabase/viz-core/echarts/graph/treemap/model/colors.unit.spec.ts
@@ -0,0 +1,36 @@
+import { color } from "metabase/ui/colors";
+import type { TreemapRow } from "metabase-types/api";
+
+import { getTreemapColors } from "./colors";
+import type { TreemapTree } from "./types";
+
+const TREE: TreemapTree = [
+ { rawName: "Doohickey", displayName: "Doohickey", value: 1, rowIndices: [0] },
+];
+
+const createRow = (row: Partial<TreemapRow>): TreemapRow => ({
+ key: "Doohickey",
+ name: "Doohickey",
+ originalName: "Doohickey",
+ color: "#000000",
+ defaultColor: false,
+ enabled: true,
+ hidden: false,
+ ...row,
+});
+
+describe("getTreemapColors", () => {
+ it("uses the palette color a group records over its stored color", () => {
+ const colors = getTreemapColors(TREE, [
+ createRow({ color_name: "accent3" }),
+ ]);
+
+ expect(colors.Doohickey).toBe(color("accent3"));
+ });
+
+ it("keeps the stored color of a group that records no palette color", () => {
+ const colors = getTreemapColors(TREE, [createRow({ color: "#123456" })]);
+
+ expect(colors.Doohickey).toBe("#123456");
+ });
+});
diff --git a/frontend/src/metabase/viz-core/echarts/pie/model/index.ts b/frontend/src/metabase/viz-core/echarts/pie/model/index.ts
index f2fe7cd33e8..2125fe5fb9e 100644
--- a/frontend/src/metabase/viz-core/echarts/pie/model/index.ts
+++ b/frontend/src/metabase/viz-core/echarts/pie/model/index.ts
@@ -9,6 +9,7 @@ import {
getRowsForStableKeys,
} from "metabase-types/api";
+import { getChartColor } from "../../../lib/color-name";
import type { ColumnDescriptor } from "../../../lib/graph/columns";
import { getNumberOr } from "../../../lib/settings/row-values";
import {
@@ -364,7 +365,7 @@ export function getPieChartModel(
const sliceTree: SliceTree = new Map();
let i = 0;
const [sliceTreeNodes, others] = _.chain(pieRowsWithValues)
- .map(({ value, color, key, name, isOther }) => {
+ .map(({ value, color, color_name, key, name, isOther }) => {
const visible = isOther
? !hiddenSlices.includes(OTHER_SLICE_KEY)
: !hiddenSlices.includes(key);
@@ -378,7 +379,7 @@ export function getPieChartModel(
rawValue: value,
normalizedPercentage,
color: getColorForRing(
- color,
+ getChartColor(color, color_name),
"inner",
colDescs.middleDimensionDesc != null,
),
diff --git a/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts
index 79c04e9ee6c..5b50739be6e 100644
--- a/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/echarts/pie/model/index.unit.spec.ts
@@ -1,3 +1,4 @@
+import { color } from "metabase/ui/colors";
import type { VisualizationSettings } from "metabase-types/api";
import {
createMockCard,
@@ -179,4 +180,130 @@ describe("getPieChartModel", () => {
["\x00___OTHER___", 6],
]);
});
+
+ it("should use the palette color a slice records over its stored color", () => {
+ // only pie.rows differs from the settings object above
+ const settingsWithColorName = {
+ ...settings,
+ "pie.rows": settings["pie.rows"]?.map((row) =>
+ row.key === "2000"
+ ? {
+ ...row,
+ color: "#123456",
+ defaultColor: false,
+ color_name: "accent3",
+ }
+ : row,
+ ),
+ } as VisualizationSettings;
+
+ const chartModel = getPieChartModel(
+ rawSeries,
+ settingsWithColorName,
+ [],
+ renderingContext,
+ );
+
+ expect(chartModel.sliceTree.get("2000")?.color).toBe(color("accent3"));
+ });
+
+ it("should keep the stored color of a slice that records no palette color", () => {
+ // only pie.rows differs from the settings object above
+ const settingsWithStoredColor = {
+ ...settings,
+ "pie.rows": settings["pie.rows"]?.map((row) =>
+ row.key === "2000"
+ ? { ...row, color: "#123456", defaultColor: false }
+ : row,
+ ),
+ } as VisualizationSettings;
+
+ const chartModel = getPieChartModel(
+ rawSeries,
+ settingsWithStoredColor,
+ [],
+ renderingContext,
+ );
+
+ expect(chartModel.sliceTree.get("2000")?.color).toBe("#123456");
+ });
+
+ describe("multiple rings", () => {
+ const ringColumns = [
+ createMockColumn({
+ name: "birth_year",
+ display_name: "Birth Year",
+ base_type: "type/Number",
+ semantic_type: "type/Number",
+ }),
+ createMockColumn({
+ name: "region",
+ display_name: "Region",
+ base_type: "type/Text",
+ semantic_type: "type/Category",
+ }),
+ createMockColumn({
+ name: "count",
+ display_name: "Count",
+ base_type: "type/Number",
+ semantic_type: "type/Number",
+ }),
+ ];
+
+ const ringRawSeries = [
+ {
+ card: createMockCard({ name: "Two ring pie", display: "pie" }),
+ data: createMockDatasetData({
+ rows: [
+ [2000, "North", 50],
+ [2000, "South", 50],
+ ],
+ cols: ringColumns,
+ }),
+ },
+ ];
+
+ // pie.rows carries the hand-picked color under test
+ const ringSettings = {
+ "pie.metric": "count",
+ "pie.dimension": ["birth_year", "region"],
+ column_settings: {},
+ column: () => ({}),
+ "pie.slice_threshold": 0,
+ "pie.rows": [
+ {
+ key: "2000",
+ name: "2000",
+ originalName: "2000",
+ color: "#123456",
+ color_name: "accent3",
+ defaultColor: false,
+ enabled: true,
+ hidden: false,
+ isOther: false,
+ },
+ ],
+ series_settings: {},
+ } as VisualizationSettings;
+
+ // Aliases must resolve for ring shades to differ
+ const ringRenderingContext: RenderingContext = {
+ ...renderingContext,
+ getColor: (name: string) => color(name),
+ };
+
+ it("derives ring shades from the recorded palette color, not the stored one", () => {
+ const chartModel = getPieChartModel(
+ ringRawSeries,
+ ringSettings,
+ [],
+ ringRenderingContext,
+ );
+
+ const slice = chartModel.sliceTree.get("2000");
+
+ expect(slice?.color).toBe(color("accent3-dark"));
+ expect(slice?.color).not.toBe("#123456");
+ });
+ });
});
diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.ts
index 78625462005..0c186cc31ab 100644
--- a/frontend/src/metabase/viz-core/index.ts
+++ b/frontend/src/metabase/viz-core/index.ts
@@ -217,6 +217,7 @@ export {
getLegendTitles,
HEAT_MAP_ZERO_COLOR,
} from "./lib/choropleth";
+export { withColorName } from "./lib/color-name";
export { getColorScale } from "./lib/color-scales";
export { groupRawSeriesMetrics, sumMetric } from "./lib/dataset";
export {
@@ -426,7 +427,7 @@ export {
getPieSortRowsDimensionSetting,
getValueFromDimensionKey,
} from "./shared/settings/pie";
-export { SERIES_SETTING_KEY } from "./shared/settings/series";
+export { getSeriesColors, SERIES_SETTING_KEY } from "./shared/settings/series";
export { getTreemapRows } from "./shared/settings/treemap";
export type {
GroupedDataset,
diff --git a/frontend/src/metabase/viz-core/lib/color-name.ts b/frontend/src/metabase/viz-core/lib/color-name.ts
new file mode 100644
index 00000000000..ad0e7cca992
--- /dev/null
+++ b/frontend/src/metabase/viz-core/lib/color-name.ts
@@ -0,0 +1,41 @@
+import { color } from "metabase/ui/colors";
+import { ALL_ACCENT_COLOR_NAMES } from "metabase/ui/colors/constants/accents";
+import type { MetabaseAccentColorKey } from "metabase/ui/colors/types";
+
+const ACCENT_COLOR_NAMES = new Set<string>(ALL_ACCENT_COLOR_NAMES);
+
+const isAccentColorName = (name: string): name is MetabaseAccentColorKey =>
+ ACCENT_COLOR_NAMES.has(name);
+
+/**
+ * The color a chart should draw with: the palette color it was given when
+ * there is one, so that it follows the active palette, and the stored value
+ * otherwise. Charts saved before palette colors were recorded keep their value.
+ */
+export const getChartColor = (
+ storedColor: string,
+ colorName?: string,
+): string =>
+ colorName != null && isAccentColorName(colorName)
+ ? color(colorName)
+ : storedColor;
+
+/**
+ * Records the palette color a chart color was picked from, so that it can
+ * follow the active palette instead of staying on the value it was given.
+ */
+export const withColorName = <T extends { color: string; color_name?: string }>(
+ row: T,
+ colorName?: string,
+): T => {
+ if (colorName != null) {
+ return { ...row, color_name: colorName };
+ }
+
+ // A color picked outside the palette has no name, and a name left over from
+ // an earlier pick would keep overriding it.
+ const next = { ...row };
+ delete next.color_name;
+
+ return next;
+};
diff --git a/frontend/src/metabase/viz-core/lib/color-name.unit.spec.ts b/frontend/src/metabase/viz-core/lib/color-name.unit.spec.ts
new file mode 100644
index 00000000000..816fece8810
--- /dev/null
+++ b/frontend/src/metabase/viz-core/lib/color-name.unit.spec.ts
@@ -0,0 +1,71 @@
+import { color } from "metabase/ui/colors";
+import { mutateColors } from "metabase/ui/colors/colors";
+
+import { getChartColor, withColorName } from "./color-name";
+
+describe("getChartColor", () => {
+ it("keeps the stored color when no palette color was recorded", () => {
+ expect(getChartColor("#123456")).toBe("#123456");
+ });
+
+ it("uses the palette color that was recorded", () => {
+ expect(getChartColor("#123456", "accent2")).toBe(color("accent2"));
+ expect(getChartColor("#123456", "accent2-light")).toBe(
+ color("accent2-light"),
+ );
+ expect(getChartColor("#123456", "accent-gray")).toBe(color("accent-gray"));
+ });
+
+ it("keeps the stored color when the recorded name is not a palette color", () => {
+ expect(getChartColor("#123456", "accent99")).toBe("#123456");
+ expect(getChartColor("#123456", "")).toBe("#123456");
+ });
+
+ describe("when the instance palette changes, as admin chart colors do", () => {
+ afterEach(() => mutateColors({}));
+
+ it("follows the new palette", () => {
+ const picked = color("accent3");
+
+ mutateColors({ accent3: "#ABCDEF" });
+
+ expect(getChartColor(picked, "accent3")).toBe("#ABCDEF");
+ });
+
+ it("leaves a color with no recorded name alone", () => {
+ const picked = color("accent3");
+
+ mutateColors({ accent3: "#ABCDEF" });
+
+ expect(getChartColor(picked)).toBe(picked);
+ });
+ });
+});
+
+describe("withColorName", () => {
+ it("records the palette color a pick came from", () => {
+ const row = { color: "#123456" };
+
+ expect(withColorName(row, "accent2")).toEqual({
+ color: "#123456",
+ color_name: "accent2",
+ });
+ });
+
+ it("drops a previously recorded palette color when the pick has none", () => {
+ const row = { color: "#123456", color_name: "accent2" };
+
+ expect(withColorName(row, undefined)).toStrictEqual({ color: "#123456" });
+ });
+
+ it("leaves the rest of the row alone", () => {
+ const row = { key: "a", color: "#123456", defaultColor: false };
+
+ expect(withColorName(row, "accent1")).toEqual({
+ key: "a",
+ color: "#123456",
+ defaultColor: false,
+ color_name: "accent1",
+ });
+ });
+});
diff --git a/frontend/src/metabase/viz-core/lib/series.ts b/frontend/src/metabase/viz-core/lib/series.ts
index 9138ff8df48..aa15293e96a 100644
--- a/frontend/src/metabase/viz-core/lib/series.ts
+++ b/frontend/src/metabase/viz-core/lib/series.ts
@@ -13,12 +13,21 @@ import type {
import { SERIES_SETTING_KEY } from "../shared/settings/series";
+import { withColorName } from "./color-name";
+
export const updateSeriesColor = (
settings: VisualizationSettings,
seriesKey: string,
- color: string,
+ hexValue: string,
+ colorName?: string,
) => {
- return assocIn(settings, [SERIES_SETTING_KEY, seriesKey, "color"], color);
+ const existing = settings[SERIES_SETTING_KEY]?.[seriesKey] ?? {};
+
+ return assocIn(
+ settings,
+ [SERIES_SETTING_KEY, seriesKey],
+ withColorName({ ...existing, color: hexValue }, colorName),
+ );
};
export const getNameForCard = (card: SeriesCard) => {
diff --git a/frontend/src/metabase/viz-core/shared/settings/pie.ts b/frontend/src/metabase/viz-core/shared/settings/pie.ts
index 29e8702f11d..8f5fcf56ae3 100644
--- a/frontend/src/metabase/viz-core/shared/settings/pie.ts
+++ b/frontend/src/metabase/viz-core/shared/settings/pie.ts
@@ -16,6 +16,7 @@ import { SLICE_THRESHOLD } from "../../echarts/pie/constants";
import { getPieColumns } from "../../echarts/pie/model";
import type { ShowWarning } from "../../echarts/types";
import { getHexColor } from "../../lib/color";
+import { getChartColor } from "../../lib/color-name";
import { getNumberOr } from "../../lib/settings/row-values";
import { getDefaultDimensionsAndMetrics } from "../../lib/utils";
import { unaggregatedDataWarningPie } from "../../lib/warnings";
@@ -184,7 +185,9 @@ export function getColors(
if (currentSettings["pie.rows"]) {
for (const row of currentSettings["pie.rows"]) {
if (!row.defaultColor && row.color) {
- existingColorMapping[row.key] = getHexColor(row.color);
+ existingColorMapping[row.key] = getHexColor(
+ getChartColor(row.color, row.color_name),
+ );
}
}
}
diff --git a/frontend/src/metabase/viz-core/shared/settings/pie.unit.spec.ts b/frontend/src/metabase/viz-core/shared/settings/pie.unit.spec.ts
index 68b7d4ecdae..6d822f8169e 100644
--- a/frontend/src/metabase/viz-core/shared/settings/pie.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/shared/settings/pie.unit.spec.ts
@@ -1,3 +1,4 @@
+import { color } from "metabase/ui/colors";
import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";
import type { PieRow, RawSeries } from "metabase-types/api";
import {
@@ -175,4 +176,34 @@ describe("getColors", () => {
),
).toBe(true);
});
+
+ it("should use the palette color a slice records over its stored color", () => {
+ // getColors only reads rows and cols off the series
+ const rawSeries = [
+ {
+ data: createMockDatasetData({
+ rows: [["Doohickey", 1]],
+ cols: [
+ createMockColumn({ name: "Category" }),
+ createMockColumn({ name: "Count" }),
+ ],
+ }),
+ },
+ ] as RawSeries;
+ const settings = {
+ "pie.metric": "Count",
+ "pie.dimension": "Category",
+ // getColors only reads the key, color and defaultColor of a row
+ "pie.rows": [
+ {
+ key: "Doohickey",
+ defaultColor: false,
+ color: "#000000",
+ color_name: "accent3",
+ },
+ ] as PieRow[],
+ };
+
+ expect(getColors(rawSeries, settings).Doohickey).toBe(color("accent3"));
+ });
});
diff --git a/frontend/src/metabase/viz-core/shared/settings/series.ts b/frontend/src/metabase/viz-core/shared/settings/series.ts
index 1702ef5a4b6..a787f5a5f57 100644
--- a/frontend/src/metabase/viz-core/shared/settings/series.ts
+++ b/frontend/src/metabase/viz-core/shared/settings/series.ts
@@ -1,8 +1,7 @@
-import { getIn } from "icepick";
-
import { getColorsForValues } from "metabase/ui/colors/charts";
import type { VisualizationSettings } from "metabase-types/api";
+import { getChartColor } from "../../lib/color-name";
import type { ComputedVisualizationSettings } from "../../types";
export const SERIES_SETTING_KEY = "series_settings";
@@ -15,10 +14,7 @@ export const getSeriesColors = (
) => {
const assignments: Record<string, string> = {};
- // Unjustified type cast. FIXME
- const seriesSettings = getIn(settings, [SERIES_SETTING_KEY]) as
- | Record<string, { color?: string; title?: string }>
- | undefined;
+ const seriesSettings = settings[SERIES_SETTING_KEY];
if (seriesSettings) {
for (const [key, seriesObject] of Object.entries(seriesSettings)) {
@@ -27,10 +23,15 @@ export const getSeriesColors = (
}
if (seriesObject.color != null) {
- assignments[key] = seriesObject.color;
+ const seriesColor = getChartColor(
+ seriesObject.color,
+ seriesObject.color_name,
+ );
+
+ assignments[key] = seriesColor;
if (seriesObject.title != null) {
- assignments[seriesObject.title] = seriesObject.color;
+ assignments[seriesObject.title] = seriesColor;
}
}
}
diff --git a/frontend/src/metabase/viz-core/shared/utils/colors.ts b/frontend/src/metabase/viz-core/shared/utils/colors.ts
index 43e7e424a82..c0625a8fd3e 100644
--- a/frontend/src/metabase/viz-core/shared/utils/colors.ts
+++ b/frontend/src/metabase/viz-core/shared/utils/colors.ts
@@ -1,6 +1,7 @@
import { getColorsForValues } from "metabase/ui/colors/charts";
import type { VisualizationSettings } from "metabase-types/api";
+import { getChartColor } from "../../lib/color-name";
import type { Series } from "../components/RowChart/types";
export const getSeriesColors = <TDatum, TSeriesInfo>(
@@ -12,7 +13,10 @@ export const getSeriesColors = <TDatum, TSeriesInfo>(
).reduce(
(mapping, [seriesName, seriesSettings]) => {
if (typeof seriesSettings?.color === "string") {
- mapping[seriesName] = seriesSettings.color;
+ mapping[seriesName] = getChartColor(
+ seriesSettings.color,
+ seriesSettings.color_name,
+ );
}
return mapping;
diff --git a/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts b/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts
index 5d6cd1e4545..dd1a8c25cdd 100644
--- a/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/shared/utils/colors.unit.spec.ts
@@ -1,3 +1,4 @@
+import { color } from "metabase/ui/colors";
import { getColorsForValues } from "metabase/ui/colors/charts";
import type { VisualizationSettings } from "metabase-types/api";
@@ -131,4 +132,38 @@ describe("getSeriesColors", () => {
},
);
});
+
+ it("should use the palette color a series records over its stored color", () => {
+ const settings = {
+ series_settings: {
+ "Series 1": { color: "#FF0000", color_name: "accent3" },
+ "Series 2": { color: "#00FF00" },
+ },
+ };
+
+ const series = [
+ {
+ seriesKey: "Series 1",
+ seriesName: "Series 1",
+ xAccessor: (d: any) => d.x,
+ yAccessor: (d: any) => d.y,
+ },
+ {
+ seriesKey: "Series 2",
+ seriesName: "Series 2",
+ xAccessor: (d: any) => d.x,
+ yAccessor: (d: any) => d.y,
+ },
+ ];
+
+ getSeriesColors(settings, series);
+
+ expect(mockGetColorsForValues).toHaveBeenCalledWith(
+ ["Series 1", "Series 2"],
+ {
+ "Series 1": color("accent3"),
+ "Series 2": "#00FF00",
+ },
+ );
+ });
});
diff --git a/frontend/src/metabase/viz-core/types/widget-props.ts b/frontend/src/metabase/viz-core/types/widget-props.ts
index ecc5aa9524d..3defb96a8a4 100644
--- a/frontend/src/metabase/viz-core/types/widget-props.ts
+++ b/frontend/src/metabase/viz-core/types/widget-props.ts
@@ -89,7 +89,11 @@ export type ChartSettingSeriesOrderProps = {
) => void;
series: Series;
hasEditSettings: boolean;
- onChangeSeriesColor: (seriesKey: string, color: string) => void;
+ onChangeSeriesColor: (
+ seriesKey: string,
+ hexValue: string,
+ colorName?: string,
+ ) => void;
onSortEnd: (newItems: ChartSettingSeriesOrderItem[]) => void;
isSortable?: boolean;
accentColorOptions?: AccentColorOptions;