The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Use square and octagonal color harmonies in embedding themes (#73535)
Sébastienf09482e08fb6
diff --git a/e2e/test/scenarios/embedding/embedding-theme-editor/theme-editor.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-editor.cy.spec.tsindex b464a383a82..d36e0d283be 100644--- a/e2e/test/scenarios/embedding/embedding-theme-editor/theme-editor.cy.spec.ts+++ b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-editor.cy.spec.ts@@ -247,15 +247,15 @@ describe(cy.log("revert button should appear after changing a main color");H.main()- .findByLabelText("Revert to default main colors")+ .findByLabelText("Reset main colors to defaults").should("be.visible");cy.log("click revert to reset main colors back to defaults");- H.main().findByLabelText("Revert to default main colors").click();+ H.main().findByLabelText("Reset main colors to defaults").click();cy.log("revert button should disappear after resetting");H.main()- .findByLabelText("Revert to default main colors")+ .findByLabelText("Reset main colors to defaults").should("not.exist");cy.log("change the brand color again");@@ -309,17 +309,15 @@ describe(cy.log("revert button should be visible since the API theme has non-default additional colors",);- cy.findByLabelText("Revert to default additional colors").should(+ cy.findByLabelText("Regenerate from brand color").should("be.visible",);cy.log("click revert to reset additional colors to defaults");- cy.findByLabelText("Revert to default additional colors").click();+ cy.findByLabelText("Regenerate from brand color").click();cy.log("revert button should disappear after resetting");- cy.findByLabelText("Revert to default additional colors").should(- "not.exist",- );+ cy.findByLabelText("Regenerate from brand color").should("not.exist");});});diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsxindex 3abae858cb5..ef641e80cfc 100644--- a/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx@@ -14,6 +14,7 @@ import {Stack,Text,TextInput,+ Tooltip,UnstyledButton,} from "metabase/ui";import type { MetabaseFontFamily } from "metabase/ui/fonts";@@ -104,15 +105,17 @@ export function EditorPanel({<Flex mb="sm" h="26" align="center" justify="space-between"><Text fw={600}>{t`Main colors`}</Text>{editor.hasMainColorChanges && (- <Button- variant="subtle"- pt="5"- size="compact-sm"- aria-label={t`Revert to default main colors`}- onClick={editor.resetMainColors}- >- <Icon name="revert" size={16} />- </Button>+ <Tooltip label={t`Reset main colors to defaults`}>+ <Button+ variant="subtle"+ pt="5"+ size="compact-sm"+ aria-label={t`Reset main colors to defaults`}+ onClick={editor.resetMainColors}+ >+ <Icon name="revert" size={16} />+ </Button>+ </Tooltip>)}</Flex><Flex gap="sm">@@ -143,15 +146,19 @@ export function EditorPanel({</Flex></UnstyledButton>- {editor.hasAdditionalColorChanges && (- <Button- variant="subtle"- size="compact-sm"- aria-label={t`Revert to default additional colors`}- onClick={editor.resetAdditionalColors}+ {editor.hasOutOfSyncAdditionalColors && (+ <Tooltip+ label={t`Regenerate filter, summarize, positive, negative, and chart colors from the brand color`}>- <Icon name="revert" size={16} />- </Button>+ <Button+ variant="subtle"+ size="compact-sm"+ aria-label={t`Regenerate from brand color`}+ onClick={editor.regenerateAdditionalColorsFromBrand}+ >+ <Icon name="revert" size={16} />+ </Button>+ </Tooltip>)}</Flex>diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsxindex 214a077e5ef..e4a901f748f 100644--- a/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx@@ -99,7 +99,14 @@ export function ResourcePreview({pos="relative"style={{ backgroundColor: theme?.colors?.background }}>- {createElement(componentName, attributes)}+ {/* `key` forces a remount when chart colors change. The embed runtime+ propagates other theme keys via CSS variables, but chart colors are+ applied through a module-level side effect on mount, so already-rendered+ charts don't pick up updates without a full remount. */}+ {createElement(componentName, {+ ...attributes,+ key: JSON.stringify(theme.colors?.charts),+ })}{isLoading && (<Boxdiff --git a/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.tsindex 0b99fa8b65f..3562d71546b 100644--- a/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts+++ b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts@@ -9,12 +9,17 @@ import {useGetEmbeddingThemeQuery,useUpdateEmbeddingThemeMutation,} from "metabase/api/embedding-theme";-import { useToast } from "metabase/common/hooks";+import { useSetting, useToast } from "metabase/common/hooks";import type {+ ChartColor,MetabaseColor,MetabaseTheme,} from "metabase/embedding-sdk/theme";+import { useDispatch } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import { suggestHarmonyColors } from "metabase/ui/colors/harmonies";import type { EmbeddingTheme } from "metabase-types/api";+import type { ColorSettings } from "metabase-types/api/settings";interface ThemeEditorState {name: string;@@ -23,26 +28,86 @@ interface ThemeEditorState {export type ThemeEditorId = number | "new";-/** Color keys that belong to the "additional colors" section. */-const ADDITIONAL_COLOR_KEYS: Exclude<MetabaseColor, "charts">[] = [- "text-secondary",- "text-tertiary",- "border",- "background-secondary",- "filter",- "summarize",- "positive",- "negative",- "shadow",-];-const PRIMARY_COLORS_KEYS: Exclude<MetabaseColor, "charts">[] = ["brand","background","text-primary",];+const chartBase = (c: ChartColor): string =>+ typeof c === "string" ? c : c.base;++const eqColor = (a: string | undefined, b: string | undefined) =>+ (a ?? "").toLowerCase() === (b ?? "").toLowerCase();++/**+ * Returns a copy of `settings` with `filter` / `summarize` / `positive` /+ * `negative` / `charts` overwritten by the values that the harmony would+ * derive from the brand color. If there is no brand color, returns the+ * settings unchanged.+ *+ * Used by the regenerate-from-brand button: the user is explicitly asking+ * to overwrite every harmony-managed color, so whitelabel customizations+ * are not respected here.+ */+const withBrandHarmony = (settings: MetabaseTheme): MetabaseTheme => {+ const brand = settings.colors?.brand;+ if (!brand) {+ return settings;+ }+ const harmony = suggestHarmonyColors(brand);+ return {+ ...settings,+ colors: {+ ...settings.colors,+ filter: harmony.filter,+ summarize: harmony.summarize,+ positive: harmony.positive,+ negative: harmony.negative,+ charts: harmony.charts,+ },+ };+};++/**+ * Seed for a fresh draft: fills harmony-managed colors with brand-derived+ * values *only when* the corresponding whitelabel key is not set. This keeps+ * a fresh draft in-sync with the harmony when no customizations exist (so+ * the regenerate button stays hidden), while still honoring any+ * `application-colors` overrides the admin has configured.+ */+const seedDraftFromHarmony = (+ settings: MetabaseTheme,+ whitelabelColors: ColorSettings,+): MetabaseTheme => {+ const brand = settings.colors?.brand;+ if (!brand) {+ return settings;+ }+ const harmony = suggestHarmonyColors(brand);+ const existingCharts = settings.colors?.charts ?? [];+ const charts: ChartColor[] = harmony.charts.map((harmonyChart, i) => {+ const accentKey = `accent${i}` as keyof ColorSettings;+ if (whitelabelColors[accentKey] !== undefined) {+ return existingCharts[i] ?? harmonyChart;+ }+ return harmonyChart;+ });+ return {+ ...settings,+ colors: {+ ...settings.colors,+ filter: whitelabelColors.filter ?? harmony.filter,+ summarize: whitelabelColors.summarize ?? harmony.summarize,+ positive: whitelabelColors.success ?? harmony.positive,+ negative: whitelabelColors.danger ?? harmony.negative,+ charts,+ },+ };+};+export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {+ const dispatch = useDispatch();const isDraft = themeId === "new";const {data: serverTheme,@@ -53,11 +118,20 @@ export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {const [updateTheme] = useUpdateEmbeddingThemeMutation();const [sendToast] = useToast();const defaultThemeSettings = useDefaultEmbeddingThemeSettings();+ const whitelabelColors = useSetting("application-colors") ?? {};- // Seed once on mount when in draft mode so the baseline is stable across renders.+ // Seed once on mount when in draft mode so the baseline is stable across+ // renders. Harmony-managed colors are pre-derived from the brand, with any+ // whitelabel overrides preserved.const [draftInitial] = useState<ThemeEditorState | null>(() =>isDraft- ? { name: t`Untitled theme`, settings: defaultThemeSettings }+ ? {+ name: t`Untitled theme`,+ settings: seedDraftFromHarmony(+ defaultThemeSettings,+ whitelabelColors,+ ),+ }: null,);@@ -94,13 +168,20 @@ export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {);const canSave = isDraft || isDirty;- const updateSettings = useCallback(- (updater: (settings: MetabaseTheme) => Partial<MetabaseTheme>) => {+ const setName = useCallback((name: string) => {+ setCurrentTheme((prev) => (prev ? { ...prev, name } : prev));+ }, []);++ const setColor = useCallback(+ (key: Exclude<MetabaseColor, "charts">, value: string) => {setCurrentTheme((prev) =>prev? {...prev,- settings: { ...prev.settings, ...updater(prev.settings) },+ settings: {+ ...prev.settings,+ colors: { ...prev.settings.colors, [key]: value.toLowerCase() },+ },}: prev,);@@ -108,30 +189,23 @@ export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {[],);- const setName = useCallback((name: string) => {- setCurrentTheme((prev) => (prev ? { ...prev, name } : prev));+ const setChartColor = useCallback((index: number, value: string) => {+ setCurrentTheme((prev) => {+ if (!prev) {+ return prev;+ }+ const charts = [...(prev.settings.colors?.charts ?? [])];+ charts[index] = value.toLowerCase();+ return {+ ...prev,+ settings: {+ ...prev.settings,+ colors: { ...prev.settings.colors, charts },+ },+ };+ });}, []);- const setColor = useCallback(- (key: Exclude<MetabaseColor, "charts">, value: string) => {- updateSettings((s) => ({- colors: { ...s.colors, [key]: value.toLowerCase() },- }));- },- [updateSettings],- );-- const setChartColor = useCallback(- (index: number, value: string) => {- updateSettings((s) => {- const charts = [...(s.colors?.charts ?? [])];- charts[index] = value.toLowerCase();- return { colors: { ...s.colors, charts } };- });- },- [updateSettings],- );-const setFontFamily = useCallback((family: string) => {setCurrentTheme((prev) => {if (!prev) {@@ -158,67 +232,86 @@ export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {});}, []);- const hasAdditionalColorChanges = useMemo(() => {+ const hasMainColorChanges = useMemo(() => {if (!currentTheme) {return false;}-const colors = currentTheme.settings.colors ?? {};const defaultColors = defaultThemeSettings.colors ?? {};-- for (const key of ADDITIONAL_COLOR_KEYS) {- if ((colors[key] ?? "") !== ((defaultColors[key] as string) ?? "")) {- return true;- }- }-- return !isEqual(colors.charts ?? [], defaultColors.charts ?? []);+ return PRIMARY_COLORS_KEYS.some(+ (key) => (colors[key] ?? "") !== ((defaultColors[key] as string) ?? ""),+ );}, [currentTheme, defaultThemeSettings]);- const hasMainColorChanges = useMemo(() => {+ /**+ * True when the current filter / summarize / positive / negative / chart colors differ+ * from what would be generated from the current brand color via the color harmony.+ * Drives the regenerate button visibility.+ */+ const hasOutOfSyncAdditionalColors = useMemo(() => {if (!currentTheme) {return false;}-const colors = currentTheme.settings.colors ?? {};- const defaultColors = defaultThemeSettings.colors ?? {};-- for (const key of PRIMARY_COLORS_KEYS) {- if ((colors[key] ?? "") !== ((defaultColors[key] as string) ?? "")) {- return true;- }+ const brand = colors.brand;+ if (!brand) {+ return false;}+ const expected = suggestHarmonyColors(brand);+ if (!eqColor(colors.filter, expected.filter)) {+ return true;+ }+ if (!eqColor(colors.summarize, expected.summarize)) {+ return true;+ }+ if (!eqColor(colors.positive, expected.positive)) {+ return true;+ }+ if (!eqColor(colors.negative, expected.negative)) {+ return true;+ }+ const currentCharts = (colors.charts ?? []).map(chartBase);+ return expected.charts.some((c, i) => !eqColor(currentCharts[i], c));+ }, [currentTheme]);- return !isEqual(colors.charts ?? [], defaultColors.charts ?? []);- }, [currentTheme, defaultThemeSettings]);-- const resetAdditionalColors = useCallback(() => {- updateSettings((s) => {- const defaultColors = defaultThemeSettings.colors ?? {};- const updatedColors = { ...s.colors };-- for (const key of ADDITIONAL_COLOR_KEYS) {- updatedColors[key] = (defaultColors[key] as string) ?? "";- }-- updatedColors.charts = defaultColors.charts ?? [];-- return { colors: updatedColors };+ const regenerateAdditionalColorsFromBrand = useCallback(() => {+ if (!currentTheme?.settings.colors?.brand) {+ return;+ }+ setCurrentTheme({+ ...currentTheme,+ settings: withBrandHarmony(currentTheme.settings),});- }, [updateSettings, defaultThemeSettings]);+ dispatch(+ addUndo({+ message: t`Filter, summarize, positive, negative, and chart colors regenerated from the brand color.`,+ actionLabel: t`Undo`,+ actions: [() => setCurrentTheme(currentTheme)],+ }),+ );+ }, [currentTheme, dispatch]);const resetMainColors = useCallback(() => {- updateSettings((s) => {- const defaultColors = defaultThemeSettings.colors ?? {};- const updatedColors = { ...s.colors };-- for (const key of PRIMARY_COLORS_KEYS) {- updatedColors[key] = (defaultColors[key] as string) ?? "";- }-- return { colors: updatedColors };+ if (!currentTheme) {+ return;+ }+ const defaultColors = defaultThemeSettings.colors ?? {};+ const updatedColors = { ...currentTheme.settings.colors };+ for (const key of PRIMARY_COLORS_KEYS) {+ updatedColors[key] = (defaultColors[key] as string) ?? "";+ }+ setCurrentTheme({+ ...currentTheme,+ settings: { ...currentTheme.settings, colors: updatedColors },});- }, [updateSettings, defaultThemeSettings]);+ dispatch(+ addUndo({+ message: t`Main colors reset to defaults.`,+ actionLabel: t`Undo`,+ actions: [() => setCurrentTheme(currentTheme)],+ }),+ );+ }, [currentTheme, defaultThemeSettings, dispatch]);const handleSave = useCallback(async (): Promise<EmbeddingTheme | null> => {if (!currentTheme) {@@ -263,8 +356,8 @@ export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {setChartColor,hasMainColorChanges,resetMainColors,- hasAdditionalColorChanges,- resetAdditionalColors,+ hasOutOfSyncAdditionalColors,+ regenerateAdditionalColorsFromBrand,setFontFamily,setFontSize,handleSave,diff --git a/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.unit.spec.tsx b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.unit.spec.tsxindex 949fdfdc56b..f83206f3a4a 100644--- a/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.unit.spec.tsx+++ b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.unit.spec.tsx@@ -1,7 +1,13 @@+import Color from "color";import fetchMock from "fetch-mock";import { act, renderHookWithProviders, waitFor } from "__support__/ui";+import type { State } from "metabase/redux/store";+import { createMockState } from "metabase/redux/store/mocks";+import { performUndo } from "metabase/redux/undo";+import { suggestHarmonyColors } from "metabase/ui/colors/harmonies";import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";+import type { ColorSettings } from "metabase-types/api/settings";import {type ThemeEditorId,@@ -20,7 +26,7 @@ const TEST_THEME: EmbeddingTheme = {updated_at: "2024-01-01T00:00:00Z",};-function setup(themeId: ThemeEditorId = 1) {+function setup(themeId: ThemeEditorId = 1, applicationColors?: ColorSettings) {if (typeof themeId === "number") {fetchMock.get(`path:/api/embed-theme/${themeId}`, TEST_THEME);fetchMock.put(`path:/api/embed-theme/${themeId}`, {@@ -29,8 +35,16 @@ function setup(themeId: ThemeEditorId = 1) {});}+ const storeInitialState = applicationColors+ ? createMockState({+ settings: { values: { "application-colors": applicationColors } },+ } as Partial<State>)+ : undefined;+return renderHookWithProviders(() => useEmbeddingThemeEditor(themeId), {withUndos: true,+ withRouter: true,+ storeInitialState,});}@@ -105,155 +119,277 @@ describe("useEmbeddingThemeEditor", () => {expect(result.current.isDirty).toBe(false);});- describe("additional colors reset", () => {- const CUSTOM_ADDITIONAL_COLORS = {- "text-secondary": "#AAAAAA",- "text-tertiary": "#BBBBBB",- border: "#CCCCCC",- "background-secondary": "#DDDDDD",- filter: "#EEEEEE",- summarize: "#FFFFFF",- positive: "#00FF00",- negative: "#FF0000",- shadow: "#333333",- };-- const THEME_WITH_CUSTOM_COLORS: EmbeddingTheme = {- ...TEST_THEME,- settings: {- ...TEST_THEME.settings,- colors: {- brand: "#FF0000",- background: "#111111",- "text-primary": "#222222",- ...CUSTOM_ADDITIONAL_COLORS,- charts: [- "#A00",- "#B00",- "#C00",- "#D00",- "#E00",- "#F00",- "#100",- "#200",- ],- },- },- };-- function setupWithCustomColors() {- fetchMock.get("path:/api/embed-theme/1", THEME_WITH_CUSTOM_COLORS);- fetchMock.put("path:/api/embed-theme/1", THEME_WITH_CUSTOM_COLORS);-- return renderHookWithProviders(() => useEmbeddingThemeEditor(1), {- withUndos: true,- });- }-- it("hasAdditionalColorChanges is false when colors match defaults", async () => {- const { result } = setup();+ describe("hasOutOfSyncAdditionalColors", () => {+ it("is false on a fresh draft — additional colors are pre-seeded from the brand harmony", async () => {+ const { result } = setup("new");++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);+ });++ it("is false when filter / summarize / positive / negative / charts match the brand-derived harmony", async () => {+ const { result } = setup("new");await waitFor(() => {expect(result.current.currentTheme).not.toBeNull();});- // TEST_THEME has no additional colors set, so they're undefined/"",- // but defaults come from useDefaultEmbeddingThemeSettings.- // After a reset, hasAdditionalColorChanges should be false.act(() => {- result.current.resetAdditionalColors();+ result.current.regenerateAdditionalColorsFromBrand();});- expect(result.current.hasAdditionalColorChanges).toBe(false);+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);});- it("hasAdditionalColorChanges is true when an additional color differs", async () => {- const { result } = setup();+ it("is true when a harmony-managed color is edited away from the derived value", async () => {+ const { result } = setup("new");await waitFor(() => {expect(result.current.currentTheme).not.toBeNull();});act(() => {- result.current.setColor("border", "#FF00FF");+ result.current.regenerateAdditionalColorsFromBrand();+ });+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);++ act(() => {+ result.current.setColor("filter", "#123456");});- expect(result.current.hasAdditionalColorChanges).toBe(true);+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(true);});- it("hasAdditionalColorChanges is true when chart colors differ", async () => {- const { result } = setup();+ it("is true when a chart color is edited away from the derived value", async () => {+ const { result } = setup("new");await waitFor(() => {expect(result.current.currentTheme).not.toBeNull();});act(() => {- result.current.setChartColor(0, "#FF00FF");+ result.current.regenerateAdditionalColorsFromBrand();+ });++ act(() => {+ result.current.setChartColor(3, "#abcdef");});- expect(result.current.hasAdditionalColorChanges).toBe(true);+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(true);});- it("hasAdditionalColorChanges is false for main color changes only", async () => {- const { result } = setup();+ it("is true when the brand changes (derived values now stale)", async () => {+ const { result } = setup("new");await waitFor(() => {expect(result.current.currentTheme).not.toBeNull();});- // Reset additional colors to defaults firstact(() => {- result.current.resetAdditionalColors();+ result.current.regenerateAdditionalColorsFromBrand();});+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);- // Change only a main coloract(() => {- result.current.setColor("brand", "#123456");+ result.current.setColor("brand", "#aa3322");});- expect(result.current.hasAdditionalColorChanges).toBe(false);+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(true);});- it("resets additional and chart colors to defaults, preserving main colors", async () => {- const { result } = setupWithCustomColors();+ it("ignores edits to non-derived colors like border", async () => {+ const { result } = setup("new");await waitFor(() => {expect(result.current.currentTheme).not.toBeNull();});- expect(result.current.hasAdditionalColorChanges).toBe(true);+ act(() => {+ result.current.regenerateAdditionalColorsFromBrand();+ });+ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);act(() => {- result.current.resetAdditionalColors();+ result.current.setColor("border", "#abcdef");+ });++ expect(result.current.hasOutOfSyncAdditionalColors).toBe(false);+ });+ });++ describe("regenerateAdditionalColorsFromBrand", () => {+ it("overwrites filter / summarize / positive / negative / charts with brand-derived values", async () => {+ const { result } = setup("new");++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ // Make derived colors stale by editing them.+ act(() => {+ result.current.setColor("filter", "#000001");+ result.current.setChartColor(0, "#000002");+ });++ const brand = result.current.currentTheme?.settings.colors?.brand ?? "";+ const expected = suggestHarmonyColors(brand);++ act(() => {+ result.current.regenerateAdditionalColorsFromBrand();});const colors = result.current.currentTheme?.settings.colors;+ expect(colors?.filter).toBe(expected.filter);+ expect(colors?.summarize).toBe(expected.summarize);+ expect(colors?.positive).toBe(expected.positive);+ expect(colors?.negative).toBe(expected.negative);+ expect(colors?.charts).toEqual(expected.charts);+ });- // Main colors should remain unchanged- expect(colors?.brand).toBe("#FF0000");- expect(colors?.background).toBe("#111111");- expect(colors?.["text-primary"]).toBe("#222222");-- // Additional colors should no longer be the custom values- expect(colors?.["text-secondary"]).not.toBe("#AAAAAA");- expect(colors?.border).not.toBe("#CCCCCC");- expect(colors?.positive).not.toBe("#00FF00");-- // Chart colors should be reset- expect(colors?.charts).not.toEqual([- "#A00",- "#B00",- "#C00",- "#D00",- "#E00",- "#F00",- "#100",- "#200",- ]);-- expect(result.current.hasAdditionalColorChanges).toBe(false);- expect(result.current.isDirty).toBe(true);+ it("queues an undo entry that restores the prior colors when invoked", async () => {+ const { result, store } = setup("new");++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ act(() => {+ result.current.setColor("filter", "#abc123");+ });+ const filterBefore = result.current.currentTheme?.settings.colors?.filter;+ expect(filterBefore).toBe("#abc123");++ await act(async () => {+ result.current.regenerateAdditionalColorsFromBrand();+ });++ expect(result.current.currentTheme?.settings.colors?.filter).not.toBe(+ filterBefore,+ );++ // The hook dispatched an undo entry; assert and trigger it programmatically.+ await waitFor(() => {+ expect(store.getState().undo).toHaveLength(1);+ });+ const undo = store.getState().undo[0];+ expect(undo.actionLabel).toBe("Undo");++ await act(async () => {+ // performUndo is a thunk; the test store wires thunk middleware at runtime.+ store.dispatch(performUndo(undo.id) as never);+ });++ expect(result.current.currentTheme?.settings.colors?.filter).toBe(+ filterBefore,+ );+ });++ it("derives the expected harmony for the Metabase brand color", async () => {+ const { result } = setup();++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ // TEST_THEME's brand is the canonical Metabase blue. Trigger the+ // generator and verify each derived color independently against the+ // harmony spec, without going through `suggestHarmonyColors` — this+ // catches regressions in either the algorithm or the wiring.+ const BRAND = "#509EE3";+ expect(result.current.currentTheme?.settings.colors?.brand).toBe(BRAND);++ await act(async () => {+ result.current.regenerateAdditionalColorsFromBrand();+ });++ const colors = result.current.currentTheme?.settings.colors;++ // Filter / summarize follow the square harmony at brand ± 90°.+ expect(colors?.filter).toBe(Color(BRAND).rotate(90).hex().toLowerCase());+ expect(colors?.summarize).toBe(+ Color(BRAND).rotate(-90).hex().toLowerCase(),+ );++ // Positive / negative anchor to fixed hues at lightness 50.+ expect(colors?.positive).toBe(+ Color(BRAND).hue(89).lightness(50).hex().toLowerCase(),+ );+ expect(colors?.negative).toBe(+ Color(BRAND).hue(359).lightness(50).hex().toLowerCase(),+ );++ // Charts: brand verbatim at index 0, then 45° rotations clockwise.+ const charts = colors?.charts as string[];+ expect(charts).toHaveLength(8);+ expect(charts[0]).toBe(BRAND.toLowerCase());+ for (let i = 1; i < 8; i++) {+ expect(charts[i]).toBe(+ Color(BRAND)+ .rotate(i * 45)+ .hex()+ .toLowerCase(),+ );+ }+ });+ });++ describe("resetMainColors", () => {+ it("resets brand / background / text-primary to defaults", async () => {+ const { result } = setup();++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ act(() => {+ result.current.setColor("brand", "#aa1111");+ });+ expect(result.current.hasMainColorChanges).toBe(true);++ act(() => {+ result.current.resetMainColors();+ });++ expect(result.current.hasMainColorChanges).toBe(false);+ });++ it("queues an undo entry that restores the prior main colors when invoked", async () => {+ const { result, store } = setup();++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ act(() => {+ result.current.setColor("brand", "#aa1111");+ });+ const brandBefore = result.current.currentTheme?.settings.colors?.brand;+ expect(brandBefore).toBe("#aa1111");++ await act(async () => {+ result.current.resetMainColors();+ });++ expect(result.current.currentTheme?.settings.colors?.brand).not.toBe(+ brandBefore,+ );++ await waitFor(() => {+ expect(store.getState().undo).toHaveLength(1);+ });+ const undo = store.getState().undo[0];++ await act(async () => {+ // performUndo is a thunk; the test store wires thunk middleware at runtime.+ store.dispatch(performUndo(undo.id) as never);+ });++ expect(result.current.currentTheme?.settings.colors?.brand).toBe(+ brandBefore,+ );});});@@ -360,6 +496,29 @@ describe("useEmbeddingThemeEditor", () => {1,);});++ it("preserves whitelabel-provided colors when seeding the draft", async () => {+ const whitelabel = {+ brand: "#8e44ad",+ filter: "#16a085",+ summarize: "#d35400",+ accent0: "#e74c3c",+ accent7: "#34495e",+ } satisfies ColorSettings;++ const { result } = setup("new", whitelabel);++ await waitFor(() => {+ expect(result.current.currentTheme).not.toBeNull();+ });++ const colors = result.current.currentTheme?.settings.colors;+ expect(colors?.brand).toBe(whitelabel.brand);+ expect(colors?.filter).toBe(whitelabel.filter);+ expect(colors?.summarize).toBe(whitelabel.summarize);+ expect(colors?.charts?.[0]).toBe(whitelabel.accent0);+ expect(colors?.charts?.[7]).toBe(whitelabel.accent7);+ });});it("reports isNotFound on API error", async () => {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsxindex c996b7e0ee2..bbf325c6d72 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SdkIframeEmbedPreview.tsx@@ -162,6 +162,11 @@ const SdkIframeEmbedPreviewInner = () => {h="100%"ref={containerRef}pos="relative"+ // `key` forces a remount when chart colors change. The embed runtime+ // propagates other theme keys via CSS variables, but chart colors are+ // applied through a module-level side effect on mount, so already-rendered+ // charts don't pick up updates without a full remount.+ key={JSON.stringify(theme?.colors?.charts)}>{match(settings).with(diff --git a/frontend/src/metabase/ui/colors/ColorHarmonyStory/ColorHarmonyDemo.tsx b/frontend/src/metabase/ui/colors/ColorHarmonyStory/ColorHarmonyDemo.tsxnew file mode 100644index 00000000000..601622a9938--- /dev/null+++ b/frontend/src/metabase/ui/colors/ColorHarmonyStory/ColorHarmonyDemo.tsx@@ -0,0 +1,218 @@+/* eslint-disable metabase/no-color-literals -- storybook demo */+/* eslint-disable metabase/no-literal-metabase-strings -- storybook demo */+/* eslint-disable i18next/no-literal-string -- storybook demo */+import Color from "color";+import { useCallback, useState } from "react";+import { match } from "ts-pattern";++import { Box, Group, Stack, Text } from "metabase/ui";+import { suggestHarmonyColors } from "metabase/ui/colors/harmonies";++import { HarmonyWheel } from "./HarmonyWheel";+import { Swatch } from "./Swatch";++type HslChannel = "hue" | "saturationl" | "lightness";++export function ColorHarmonyDemo() {+ const [brand, setBrand] = useState("#509EE2");+ const c = Color(brand);+ const harmony = suggestHarmonyColors(brand);++ const handleHsl = useCallback(+ (channel: HslChannel) => (e: React.ChangeEvent<HTMLInputElement>) => {+ const value = Number(e.currentTarget.value);+ const next = match(channel)+ .with("hue", () => c.hue(value))+ .with("saturationl", () => c.saturationl(value))+ .with("lightness", () => c.lightness(value))+ .exhaustive();+ setBrand(next.hex().toLowerCase());+ },+ [c],+ );++ return (+ <Box p={48} style={{ background: "#fafafa", minHeight: "100vh" }}>+ <Stack gap="xl" maw={1180} mx="auto">+ <Stack gap="md">+ <Text fz={28} fw={700}>+ Color Harmony+ </Text>+ <Text c="text-secondary" maw={620}>+ Square harmony places filter and summarize on the perpendicular axes+ from the brand. Octagonal harmony spreads the eight chart colors at+ 45° increments. Positive and negative anchor to fixed hues.+ </Text>+ </Stack>++ <Group align="flex-start" gap={48} wrap="wrap">+ <HarmonyWheel brand={brand} onBrandChange={setBrand} />++ <Stack gap="xl" miw={260} style={{ flex: 1 }}>+ <BrandSummary brand={brand} onBrandChange={setBrand} />++ <HslSlider+ label="Hue"+ value={Math.round(c.hue())}+ max={359}+ valueLabel={`${Math.round(c.hue())}°`}+ onChange={handleHsl("hue")}+ />+ <HslSlider+ label="Saturation"+ value={Math.round(c.saturationl())}+ max={100}+ valueLabel={`${Math.round(c.saturationl())}%`}+ onChange={handleHsl("saturationl")}+ />+ <HslSlider+ label="Lightness"+ value={Math.round(c.lightness())}+ max={100}+ valueLabel={`${Math.round(c.lightness())}%`}+ onChange={handleHsl("lightness")}+ />++ <Text size="xs" c="text-secondary" lh={1.5}>+ Drag the hue ring to rotate the brand, or use the sliders. Click+ the swatch above to pick an exact hex. Saturation under 20% falls+ back to a fixed default palette.+ </Text>++ <Stack gap="sm">+ <Text size="xs" fw={600} c="text-secondary">+ Resolved palette+ </Text>+ <Group gap="md" wrap="wrap">+ <Swatch label="Filter" hex={harmony.filter} size={20} />+ <Swatch label="Summarize" hex={harmony.summarize} size={20} />+ <Swatch label="Positive" hex={harmony.positive} size={20} />+ <Swatch label="Negative" hex={harmony.negative} size={20} />+ </Group>+ <Box style={{ height: 1, background: "rgba(0,0,0,0.08)" }} />+ <Group gap="md" wrap="wrap">+ {harmony.charts.map((chart, i) => (+ <Swatch+ key={i}+ label={`Chart ${i + 1}`}+ hex={chart}+ size={20}+ />+ ))}+ </Group>+ </Stack>++ <Stack gap="xs">+ <Text size="xs" fw={600} c="text-secondary">+ Where this is used+ </Text>+ <Text size="xs" c="text-secondary" lh={1.5}>+ The embedding theme editor (Admin → Embedding → Themes) lets+ admins create named themes that their customers' embedded+ Metabase will adopt. Hand-picking twelve colors that work+ together is tedious and easy to get wrong, so the editor seeds+ the secondary palette from the brand color via this harmony:+ filter and summarize sit on perpendicular axes (square), charts+ 1–8 fan out at 45° (octagonal), and positive/negative anchor to+ fixed green/red hues at lightness 50.+ </Text>+ </Stack>+ </Stack>+ </Group>+ </Stack>+ </Box>+ );+}++function BrandSummary({+ brand,+ onBrandChange,+}: {+ brand: string;+ onBrandChange: (next: string) => void;+}) {+ const c = Color(brand);+ return (+ <Stack gap={6}>+ <Text size="sm" fw={600} c="text-secondary">+ Brand color+ </Text>+ <Group gap="sm" align="center">+ <Box+ component="label"+ w={48}+ h={48}+ style={{+ background: brand,+ borderRadius: 8,+ border: "1px solid rgba(0,0,0,0.08)",+ cursor: "pointer",+ position: "relative",+ overflow: "hidden",+ flexShrink: 0,+ }}+ title="Click to pick a color"+ >+ <input+ type="color"+ value={brand}+ onChange={(e) => onBrandChange(e.currentTarget.value)}+ style={{+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ opacity: 0,+ cursor: "pointer",+ border: "none",+ padding: 0,+ }}+ />+ </Box>+ <Stack gap={0}>+ <Text fw={600} ff="monospace">+ {brand}+ </Text>+ <Text size="xs" c="text-secondary">+ {`hsl(${Math.round(c.hue())}°, ${Math.round(c.saturationl())}%, ${Math.round(c.lightness())}%)`}+ </Text>+ </Stack>+ </Group>+ </Stack>+ );+}++function HslSlider({+ label,+ value,+ max,+ valueLabel,+ onChange,+}: {+ label: string;+ value: number;+ max: number;+ valueLabel: string;+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;+}) {+ return (+ <Stack gap="xs">+ <Group gap="xs" justify="space-between">+ <Text size="xs" fw={600} c="text-secondary">+ {label}+ </Text>+ <Text size="xs" c="text-secondary" ff="monospace">+ {valueLabel}+ </Text>+ </Group>+ <input+ type="range"+ min={0}+ max={max}+ value={value}+ onChange={onChange}+ style={{ width: "100%" }}+ />+ </Stack>+ );+}diff --git a/frontend/src/metabase/ui/colors/ColorHarmonyStory/HarmonyWheel.tsx b/frontend/src/metabase/ui/colors/ColorHarmonyStory/HarmonyWheel.tsxnew file mode 100644index 00000000000..b0da76a14d9--- /dev/null+++ b/frontend/src/metabase/ui/colors/ColorHarmonyStory/HarmonyWheel.tsx@@ -0,0 +1,357 @@+/* eslint-disable metabase/no-color-literals -- storybook demo */+import Color from "color";+import { useCallback, useRef, useState } from "react";++import { Box } from "metabase/ui";+import { suggestHarmonyColors } from "metabase/ui/colors/harmonies";++import { PillLabel } from "./PillLabel";+import {+ ANCHOR_MARKER_RADIUS,+ BRAND_SWATCH_RADIUS,+ CHART_SWATCH_RADIUS,+ HUE_GRADIENT_STOPS,+ RING_INNER,+ RING_OUTER,+ SQUARE_SIDE_SWATCH_RADIUS,+ VERTEX_RADIUS,+ WHEEL_CENTER_X,+ WHEEL_CENTER_Y,+ WHEEL_HEIGHT,+ WHEEL_WIDTH,+ isLightColor,+ polarPoint,+} from "./geometry";++const POSITIVE_HUE = 89;+const NEGATIVE_HUE = 359;+const SQUARE_INDICES = [0, 2, 4, 6] as const;++interface HarmonyWheelProps {+ brand: string;+ onBrandChange: (next: string) => void;+}++/**+ * Interactive hue wheel that visualises the brand harmony.+ *+ * - The colored donut is a `conic-gradient` masked into a ring.+ * - Eight chart-color dots sit on the octagonal vertices (brand + i·45°).+ * - The square overlay highlights the four square-harmony positions+ * (brand, filter, ignored complement, summarize).+ * - Positive (hue 89) and negative (hue 359) markers anchor outside the ring.+ * - A transparent glass layer on top of the SVG owns the drag gesture: the+ * brand hue rotates by the cursor's angular delta from where it was grabbed,+ * so the swatch never teleports.+ */+export function HarmonyWheel({ brand, onBrandChange }: HarmonyWheelProps) {+ const c = Color(brand);+ const brandHue = c.hue();++ const harmony = suggestHarmonyColors(brand);++ const octVertices = Array.from({ length: 8 }, (_, i) => {+ const hue = (brandHue + i * 45 + 360) % 360;+ const [x, y] = polarPoint(VERTEX_RADIUS, hue);+ return { hue, x, y, color: harmony.charts[i] };+ });++ const squarePoints = SQUARE_INDICES.map((i) => octVertices[i]);++ const [posX, posY] = polarPoint(RING_OUTER + 26, POSITIVE_HUE);+ const [negX, negY] = polarPoint(RING_OUTER + 26, NEGATIVE_HUE);++ const [isDragging, setIsDragging] = useState(false);+ const brandRef = useRef(brand);+ brandRef.current = brand;++ const handleGlassPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ const layer = e.currentTarget;+ const rect = layer.getBoundingClientRect();+ const cx = rect.left + rect.width / 2;+ const cy = rect.top + rect.height / 2;++ const thetaAt = (clientX: number, clientY: number) =>+ (Math.atan2(clientY - cy, clientX - cx) * 180) / Math.PI;++ const originTheta = thetaAt(e.clientX, e.clientY);+ const originHue = Color(brandRef.current).hue();++ setIsDragging(true);++ const onMove = (ev: PointerEvent) => {+ const delta = thetaAt(ev.clientX, ev.clientY) - originTheta;+ const newHue = (((originHue + delta) % 360) + 360) % 360;+ onBrandChange(Color(brandRef.current).hue(newHue).hex().toLowerCase());+ };+ const onEnd = () => {+ setIsDragging(false);+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onEnd);+ window.removeEventListener("pointercancel", onEnd);+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onEnd);+ window.addEventListener("pointercancel", onEnd);+ },+ [onBrandChange],+ );++ return (+ <Box+ style={{+ position: "relative",+ width: WHEEL_WIDTH,+ height: WHEEL_HEIGHT,+ flexShrink: 0,+ userSelect: isDragging ? "none" : "auto",+ }}+ >+ {/* Hue donut */}+ <Box+ style={{+ position: "absolute",+ left: WHEEL_CENTER_X - RING_OUTER,+ top: WHEEL_CENTER_Y - RING_OUTER,+ width: RING_OUTER * 2,+ height: RING_OUTER * 2,+ borderRadius: "50%",+ background: `conic-gradient(from 0deg, ${HUE_GRADIENT_STOPS})`,+ maskImage: `radial-gradient(circle, transparent ${RING_INNER}px, black ${RING_INNER + 1}px, black ${RING_OUTER}px, transparent ${RING_OUTER + 1}px)`,+ WebkitMaskImage: `radial-gradient(circle, transparent ${RING_INNER}px, black ${RING_INNER + 1}px, black ${RING_OUTER}px, transparent ${RING_OUTER + 1}px)`,+ boxShadow: "0 12px 36px rgba(0,0,0,0.08)",+ }}+ />++ <svg+ width={WHEEL_WIDTH}+ height={WHEEL_HEIGHT}+ style={{ position: "absolute", inset: 0, pointerEvents: "none" }}+ >+ <polygon+ points={octVertices.map((v) => `${v.x},${v.y}`).join(" ")}+ fill="rgba(0,0,0,0.025)"+ stroke="rgba(0,0,0,0.28)"+ strokeWidth={1.5}+ strokeDasharray="4 3"+ />++ <polygon+ points={squarePoints.map((v) => `${v.x},${v.y}`).join(" ")}+ fill="none"+ stroke="rgba(0,0,0,0.45)"+ strokeWidth={2}+ />++ {octVertices.map((v, i) => (+ <VertexDot key={i} index={i} x={v.x} y={v.y} color={v.color} />+ ))}++ <CenterSwatch brand={brand} />++ <ExternalMarker+ hue={POSITIVE_HUE}+ x={posX}+ y={posY}+ color={harmony.positive}+ />+ <ExternalMarker+ hue={NEGATIVE_HUE}+ x={negX}+ y={negY}+ color={harmony.negative}+ />+ </svg>++ {/* Every label sits on its swatch's radial line, with its inner edge+ touching the swatch's outer edge — see PillLabel. */}+ <PillLabel+ x={octVertices[0].x}+ y={octVertices[0].y}+ swatchRadius={BRAND_SWATCH_RADIUS}+ text="Brand"+ emphasis+ />+ <PillLabel+ x={octVertices[2].x}+ y={octVertices[2].y}+ swatchRadius={SQUARE_SIDE_SWATCH_RADIUS}+ text="Filter"+ emphasis+ />+ <PillLabel+ x={octVertices[6].x}+ y={octVertices[6].y}+ swatchRadius={SQUARE_SIDE_SWATCH_RADIUS}+ text="Summarize"+ emphasis+ />+ <PillLabel+ x={octVertices[4].x}+ y={octVertices[4].y}+ swatchRadius={CHART_SWATCH_RADIUS}+ text="Ignored"+ muted+ />+ <PillLabel+ x={posX}+ y={posY}+ swatchRadius={ANCHOR_MARKER_RADIUS}+ text="Positive"+ />+ <PillLabel+ x={negX}+ y={negY}+ swatchRadius={ANCHOR_MARKER_RADIUS}+ text="Negative"+ />++ {/* Glass layer: a square overlay sitting on top of the SVG that owns the+ drag gesture. Centered with the wheel; pointer-down anywhere on it+ starts a drag, and the brand hue rotates by the cursor's angular+ delta from grab time — no jumps, no narrow zone. */}+ <Box+ onPointerDown={handleGlassPointerDown}+ style={{+ position: "absolute",+ left: WHEEL_CENTER_X - RING_OUTER - 10,+ top: WHEEL_CENTER_Y - RING_OUTER - 10,+ width: (RING_OUTER + 10) * 2,+ height: (RING_OUTER + 10) * 2,+ cursor: isDragging ? "grabbing" : "grab",+ touchAction: "none",+ background: "transparent",+ }}+ />+ </Box>+ );+}++function VertexDot({+ index,+ x,+ y,+ color,+}: {+ index: number;+ x: number;+ y: number;+ color: string;+}) {+ const isBrand = index === 0;+ const isComplement = index === 4;+ const isFilter = index === 2;+ const isSummarize = index === 6;+ const isSquareSide = isFilter || isSummarize;+ const r = isBrand+ ? BRAND_SWATCH_RADIUS+ : isSquareSide+ ? SQUARE_SIDE_SWATCH_RADIUS+ : CHART_SWATCH_RADIUS;++ return (+ <g transform={`translate(${x},${y})`}>+ {isBrand && (+ <circle+ r={r + 7}+ fill="none"+ stroke="rgba(0,0,0,0.5)"+ strokeWidth={2}+ strokeDasharray="2 3"+ />+ )}+ <circle+ r={r}+ fill={color}+ stroke="white"+ strokeWidth={3}+ style={{ filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.18))" }}+ />+ {isComplement && (+ <>+ <line+ x1={-7}+ y1={-7}+ x2={7}+ y2={7}+ stroke="white"+ strokeWidth={2.5}+ strokeLinecap="round"+ />+ <line+ x1={-7}+ y1={7}+ x2={7}+ y2={-7}+ stroke="white"+ strokeWidth={2.5}+ strokeLinecap="round"+ />+ </>+ )}+ </g>+ );+}++function CenterSwatch({ brand }: { brand: string }) {+ return (+ <>+ <circle+ cx={WHEEL_CENTER_X}+ cy={WHEEL_CENTER_Y}+ r={66}+ fill={brand}+ stroke="white"+ strokeWidth={5}+ style={{ filter: "drop-shadow(0 4px 12px rgba(0,0,0,0.14))" }}+ />+ <text+ x={WHEEL_CENTER_X}+ y={WHEEL_CENTER_Y + 4}+ textAnchor="middle"+ fontSize={13}+ fontWeight={600}+ fill={isLightColor(brand) ? "#1c1c1f" : "#ffffff"}+ fontFamily="ui-monospace, SFMono-Regular, Menlo, monospace"+ >+ {brand}+ </text>+ </>+ );+}++function ExternalMarker({+ hue,+ x,+ y,+ color,+}: {+ hue: number;+ x: number;+ y: number;+ color: string;+}) {+ const [ringX, ringY] = polarPoint(RING_OUTER + 4, hue);+ return (+ <g>+ <line+ x1={ringX}+ y1={ringY}+ x2={x}+ y2={y}+ stroke="rgba(0,0,0,0.25)"+ strokeWidth={1}+ />+ <circle+ cx={x}+ cy={y}+ r={ANCHOR_MARKER_RADIUS}+ fill={color}+ stroke="white"+ strokeWidth={2.5}+ style={{ filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.18))" }}+ />+ </g>+ );+}diff --git a/frontend/src/metabase/ui/colors/ColorHarmonyStory/PillLabel.tsx b/frontend/src/metabase/ui/colors/ColorHarmonyStory/PillLabel.tsxnew file mode 100644index 00000000000..abe7ed36fc8--- /dev/null+++ b/frontend/src/metabase/ui/colors/ColorHarmonyStory/PillLabel.tsx@@ -0,0 +1,153 @@+/* eslint-disable metabase/no-color-literals -- storybook demo */+import { useLayoutEffect, useRef, useState } from "react";++import { Box } from "metabase/ui";++import {+ WHEEL_CENTER_X,+ WHEEL_CENTER_Y,+ WHEEL_LABEL_PADDING,+} from "./geometry";++interface PillLabelProps {+ /** Center of the swatch the label is attached to. */+ x: number;+ y: number;+ /**+ * Visible radius of the swatch (in pixels). The label's closest point+ * (treating the pill as a stadium / discorectangle) is placed at exactly+ * `swatchRadius + WHEEL_LABEL_PADDING` from the swatch center, so the gap between+ * the swatch's outer edge and the label is uniform at every angle.+ */+ swatchRadius: number;+ text: string;+ emphasis?: boolean;+ muted?: boolean;+}++interface Size {+ width: number;+ height: number;+}++/**+ * Solves for the distance `t` between the swatch center and the label center+ * such that the closest point of the label (modelled as a stadium — a+ * rectangle of size (W−H)×H flanked by two semicircular caps of radius H/2,+ * which is exactly what `borderRadius: 999` produces for a pill) is `D` away+ * from the swatch center.+ *+ * Two regimes:+ *+ * - **Cap regime** (closest point lies on one of the rounded ends): the+ * swatch sits "east" or "west" of the central segment, beyond its+ * endpoints. Distance from swatch to a cap-end equals `D' = D + H/2` from+ * the cap center, giving a quadratic in `t`:+ * `(t·|cos θ| − halfFlat)² + (t·sin θ)² = D'²`,+ * solved as `t = halfFlat·|cos θ| + √(D'² − halfFlat²·sin²θ)`.+ *+ * - **Flat regime** (closest point lies on the rectangular top/bottom): the+ * swatch sits "above" or "below" within the central segment's x-range.+ * The closest point is the perpendicular foot on the flat side, so+ * `D' = t·|sin θ|`, giving `t = D' / |sin θ|`.+ *+ * Cardinal-aligned labels collapse to the trivial answers (`W/2 + D` for+ * east/west, `D + H/2` for north/south).+ */+const labelDistanceFromSwatch = (+ unitX: number,+ unitY: number,+ size: Size,+ D: number,+): number => {+ const { width: W, height: H } = size;+ const halfFlat = Math.max(0, (W - H) / 2);+ const Dprime = D + H / 2;++ const absCos = Math.abs(unitX);+ const absSin = Math.abs(unitY);++ // Cap regime+ const radicand = Dprime * Dprime - halfFlat * halfFlat * absSin * absSin;+ const tCap = halfFlat * absCos + Math.sqrt(Math.max(0, radicand));++ // The cap solution is valid when the projection of the swatch onto the+ // label's x-axis falls outside the central segment. Otherwise the closest+ // point is on the flat top/bottom and we use the perpendicular distance.+ if (tCap * absCos > halfFlat) {+ return tCap;+ }++ return Dprime / Math.max(absSin, 1e-6);+};++export function PillLabel({+ x,+ y,+ swatchRadius,+ text,+ emphasis = false,+ muted = false,+}: PillLabelProps) {+ const ref = useRef<HTMLDivElement>(null);+ const [size, setSize] = useState<Size | null>(null);++ // Measure synchronously after layout so the next frame paints the label at+ // its solved position. Skip updates when the size hasn't meaningfully+ // changed to avoid a re-render loop.+ useLayoutEffect(() => {+ if (!ref.current) {+ return;+ }+ const rect = ref.current.getBoundingClientRect();+ setSize((prev) => {+ if (+ prev &&+ Math.abs(prev.width - rect.width) < 0.5 &&+ Math.abs(prev.height - rect.height) < 0.5+ ) {+ return prev;+ }+ return { width: rect.width, height: rect.height };+ });+ }, []);++ const dx = x - WHEEL_CENTER_X;+ const dy = y - WHEEL_CENTER_Y;+ const r = Math.hypot(dx, dy) || 1;+ const ux = dx / r;+ const uy = dy / r;++ const D = swatchRadius + WHEEL_LABEL_PADDING;+ const distFromSwatch = size ? labelDistanceFromSwatch(ux, uy, size, D) : 0;+ const totalR = r + distFromSwatch;++ const lx = WHEEL_CENTER_X + ux * totalR;+ const ly = WHEEL_CENTER_Y + uy * totalR;++ return (+ <Box+ ref={ref}+ style={{+ position: "absolute",+ left: lx,+ top: ly,+ transform: "translate(-50%, -50%)",+ // Hide on the very first paint until we've measured the label;+ // otherwise the label flashes one frame at distFromSwatch = 0.+ opacity: size ? 1 : 0,+ fontSize: 11,+ fontWeight: emphasis ? 600 : muted ? 400 : 500,+ color: muted ? "rgba(0,0,0,0.5)" : "rgba(0,0,0,0.85)",+ background: "rgba(255,255,255,0.95)",+ padding: "3px 8px",+ borderRadius: 999,+ whiteSpace: "nowrap",+ pointerEvents: "none",+ boxShadow: "0 1px 3px rgba(0,0,0,0.08), 0 0 0 1px rgba(0,0,0,0.05)",+ }}+ >+ {text}+ </Box>+ );+}diff --git a/frontend/src/metabase/ui/colors/ColorHarmonyStory/Swatch.tsx b/frontend/src/metabase/ui/colors/ColorHarmonyStory/Swatch.tsxnew file mode 100644index 00000000000..7feaa2408e3--- /dev/null+++ b/frontend/src/metabase/ui/colors/ColorHarmonyStory/Swatch.tsx@@ -0,0 +1,35 @@+/* eslint-disable metabase/no-color-literals -- storybook demo */+import { Box, Stack, Text } from "metabase/ui";++interface SwatchProps {+ label: string;+ hex: string;+ size?: number;+}++/**+ * A small color swatch with its label and hex value. Used in the resolved+ * palette section under the harmony wheel.+ */+export function Swatch({ label, hex, size = 32 }: SwatchProps) {+ return (+ <Stack gap={4} align="center">+ <Box+ w={size}+ h={size}+ style={{+ background: hex,+ borderRadius: size / 2,+ border: "1px solid rgba(0,0,0,0.08)",+ boxShadow: "0 1px 3px rgba(0,0,0,0.08)",+ }}+ />+ <Text size="xs" fw={500}>+ {label}+ </Text>+ <Text size="xs" c="text-secondary" ff="monospace">+ {hex}+ </Text>+ </Stack>+ );+}diff --git a/frontend/src/metabase/ui/colors/ColorHarmonyStory/geometry.ts b/frontend/src/metabase/ui/colors/ColorHarmonyStory/geometry.tsnew file mode 100644index 00000000000..885d2a9df92--- /dev/null+++ b/frontend/src/metabase/ui/colors/ColorHarmonyStory/geometry.ts@@ -0,0 +1,55 @@+import Color from "color";++/** Container dimensions. The wheel diameter is taken from the smaller of the+ * two so the wheel always fits, with the remainder distributed as label halo+ * on every side. */+export const WHEEL_WIDTH = 720;+export const WHEEL_HEIGHT = 720;++export const WHEEL_CENTER_X = WHEEL_WIDTH / 2;+export const WHEEL_CENTER_Y = WHEEL_HEIGHT / 2;++const SHORT_SIDE = Math.min(WHEEL_WIDTH, WHEEL_HEIGHT);++/** Padding between the wheel's outer edge and the container edge (per side).+ * Sized to accommodate the longest label plus its swatch. */+const LABEL_HALO = 140;++export const RING_OUTER = SHORT_SIDE / 2 - LABEL_HALO;+export const RING_INNER = RING_OUTER - 35;+export const VERTEX_RADIUS = RING_OUTER - 18;++// Swatch radii, in SVG pixels — kept in geometry so labels can position+// themselves to touch each swatch's outer edge.+export const BRAND_SWATCH_RADIUS = 22;+export const SQUARE_SIDE_SWATCH_RADIUS = 18;+export const CHART_SWATCH_RADIUS = 13;+export const ANCHOR_MARKER_RADIUS = 11;++/** Extra space between every label's inner edge and its swatch's outer edge.+ * Set to 0 to make labels touch their swatches; raise to push every label+ * further from the wheel center uniformly. */+export const WHEEL_LABEL_PADDING = 10;++/**+ * Maps a hue (0–360°) to an (x, y) point at the given radius around the wheel+ * center. Hue 0 sits at the top, increasing clockwise — matched to the+ * `conic-gradient(from 0deg, …)` that paints the hue ring.+ */+export const polarPoint = (+ radius: number,+ hueDeg: number,+): [number, number] => {+ const rad = ((hueDeg - 90) * Math.PI) / 180;+ return [+ WHEEL_CENTER_X + radius * Math.cos(rad),+ WHEEL_CENTER_Y + radius * Math.sin(rad),+ ];+};++export const HUE_GRADIENT_STOPS = Array.from(+ { length: 13 },+ (_, i) => `hsl(${i * 30}, 100%, 50%)`,+).join(", ");++export const isLightColor = (hex: string) => Color(hex).isLight();diff --git a/frontend/src/metabase/ui/colors/colors.stories.tsx b/frontend/src/metabase/ui/colors/colors.stories.tsxindex 18f6a13db5c..0cf28859e01 100644--- a/frontend/src/metabase/ui/colors/colors.stories.tsx+++ b/frontend/src/metabase/ui/colors/colors.stories.tsx@@ -1,5 +1,6 @@import { Card, Flex, Text } from "metabase/ui";+import { ColorHarmonyDemo } from "./ColorHarmonyStory/ColorHarmonyDemo";import { colors } from "./colors";export default {@@ -30,3 +31,10 @@ export function Default() {</Flex>);}++export function ColorHarmony() {+ return <ColorHarmonyDemo />;+}+// Interactive demo: HSL sliders + draggable hue ring make the rendered output+// non-deterministic across snapshots, so skip Loki.+ColorHarmony.parameters = { loki: { skip: true } };diff --git a/frontend/src/metabase/ui/colors/derive-theme.ts b/frontend/src/metabase/ui/colors/derive-theme.tsindex bda81f9eed8..3eaeafcb729 100644--- a/frontend/src/metabase/ui/colors/derive-theme.ts+++ b/frontend/src/metabase/ui/colors/derive-theme.ts@@ -19,7 +19,6 @@ import type {* Priority: base theme colors < appearance settings whitelabel colors < modular embedding theme overrides** TODO(EMB-984): generate lightness stops based on a single color- * TODO(EMB-1013): generate square and octagonal color harmonies* TODO(EMB-1016): derive full color palette based on the given color object*/export function deriveFullMetabaseTheme({diff --git a/frontend/src/metabase/ui/colors/harmonies.ts b/frontend/src/metabase/ui/colors/harmonies.tsnew file mode 100644index 00000000000..2b3ae29b890--- /dev/null+++ b/frontend/src/metabase/ui/colors/harmonies.ts@@ -0,0 +1,86 @@+import Color from "color";++import { DEFAULT_ACCENT_COLORS } from "./constants/accent-colors";+import { METABASE_LIGHT_THEME } from "./constants/themes/light";++type ColorInstance = ReturnType<typeof Color>;++const SATURATION_FALLBACK_THRESHOLD = 20;++const FILTER_HUE_OFFSET = 90;+const SUMMARIZE_HUE_OFFSET = -90;++const POSITIVE_HUE = 89;+const NEGATIVE_HUE = 359;+const POSITIVE_NEGATIVE_LIGHTNESS = 50;++export interface HarmonyColors {+ filter: string;+ summarize: string;+ positive: string;+ negative: string;+ charts: string[];+}++const toHex = (c: ColorInstance) => c.hex().toLowerCase();++const normalize = (cssColor: string) => toHex(Color(cssColor));++const FALLBACK: HarmonyColors = {+ filter: normalize(METABASE_LIGHT_THEME.colors.filter),+ summarize: normalize(METABASE_LIGHT_THEME.colors.summarize),+ positive: normalize(METABASE_LIGHT_THEME.colors.success),+ negative: normalize(METABASE_LIGHT_THEME.colors.danger),+ charts: DEFAULT_ACCENT_COLORS.flatMap((c) => {+ if (c == null) {+ return [];+ }+ return [normalize(typeof c === "string" ? c : c.base)];+ }),+};+Object.freeze(FALLBACK);+Object.freeze(FALLBACK.charts);++const rotated = (brand: ColorInstance, degrees: number) =>+ toHex(brand.rotate(degrees));++/**+ * Derives accessory colors and an 8-color chart palette from a brand color.+ *+ * - `filter` and `summarize` use the square color harmony (brand ±90°), preserving+ * the brand's lightness so they read at the same visual weight.+ * - `positive` and `negative` anchor to fixed hues (green / red) at lightness 50,+ * keeping the brand's saturation so they fit the palette tonally.+ * - `charts[0]` is the brand color itself; `charts[1..7]` follow the octagonal+ * color harmony at 45° increments, each preserving the brand's lightness.+ *+ * If the brand color's HSL saturation is below ~20%, returns a fixed default+ * palette regardless — rotations off a near-grey hue produce visually+ * indistinguishable colors.+ */+export const suggestHarmonyColors = (brand: string): HarmonyColors => {+ const brandColor = Color(brand);++ if (brandColor.saturationl() < SATURATION_FALLBACK_THRESHOLD) {+ return FALLBACK;+ }++ const charts = [+ toHex(brandColor),+ ...Array.from({ length: 7 }, (_, i) => rotated(brandColor, (i + 1) * 45)),+ ];++ return {+ filter: rotated(brandColor, FILTER_HUE_OFFSET),+ summarize: rotated(brandColor, SUMMARIZE_HUE_OFFSET),+ positive: toHex(+ brandColor.hue(POSITIVE_HUE).lightness(POSITIVE_NEGATIVE_LIGHTNESS),+ ),+ negative: toHex(+ brandColor.hue(NEGATIVE_HUE).lightness(POSITIVE_NEGATIVE_LIGHTNESS),+ ),+ charts,+ };+};++export const DEFAULT_HARMONY_COLORS = FALLBACK;diff --git a/frontend/src/metabase/ui/colors/harmonies.unit.spec.ts b/frontend/src/metabase/ui/colors/harmonies.unit.spec.tsnew file mode 100644index 00000000000..ab1f85ae949--- /dev/null+++ b/frontend/src/metabase/ui/colors/harmonies.unit.spec.ts@@ -0,0 +1,104 @@+import Color from "color";++import { DEFAULT_HARMONY_COLORS, suggestHarmonyColors } from "./harmonies";++const BRAND = "#509ee3";++describe("suggestHarmonyColors", () => {+ describe("low-saturation fallback", () => {+ it.each([+ ["pure grey", "#808080"],+ ["off-white", "#eeeeee"],+ ["near-black", "#222222"],+ ])("returns the default palette for %s", (_label, color) => {+ expect(suggestHarmonyColors(color)).toEqual(DEFAULT_HARMONY_COLORS);+ });+ });++ describe("chart colors (octagonal harmony)", () => {+ const result = suggestHarmonyColors(BRAND);++ it("returns 8 chart colors", () => {+ expect(result.charts).toHaveLength(8);+ });++ it("uses the brand color verbatim for chart[0]", () => {+ expect(result.charts[0]).toBe(BRAND.toLowerCase());+ });++ it("places chart[1..7] at 45° increments from the brand hue", () => {+ const brandHue = Color(BRAND).hue();+ result.charts.slice(1).forEach((chart, i) => {+ const expectedHue = (brandHue + (i + 1) * 45) % 360;+ const actualHue = Color(chart).hue();+ expect(Math.abs(actualHue - expectedHue)).toBeLessThan(1);+ });+ });++ it("preserves brand saturation and lightness across chart[1..7]", () => {+ const brand = Color(BRAND);+ result.charts.slice(1).forEach((chart) => {+ const c = Color(chart);+ expect(Math.abs(c.saturationl() - brand.saturationl())).toBeLessThan(1);+ expect(Math.abs(c.lightness() - brand.lightness())).toBeLessThan(1);+ });+ });+ });++ describe("filter and summarize (square harmony)", () => {+ const result = suggestHarmonyColors(BRAND);++ it("derives filter at brand+90° and summarize at brand-90°", () => {+ const brandHue = Color(BRAND).hue();+ expect(+ Math.abs(Color(result.filter).hue() - ((brandHue + 90) % 360)),+ ).toBeLessThan(1);+ expect(+ Math.abs(Color(result.summarize).hue() - ((brandHue + 270) % 360)),+ ).toBeLessThan(1);+ });++ it("preserves brand lightness for filter and summarize", () => {+ const brand = Color(BRAND);+ expect(+ Math.abs(Color(result.filter).lightness() - brand.lightness()),+ ).toBeLessThan(1);+ expect(+ Math.abs(Color(result.summarize).lightness() - brand.lightness()),+ ).toBeLessThan(1);+ });+ });++ describe("positive and negative", () => {+ const result = suggestHarmonyColors(BRAND);++ it("anchors positive at hue 89°", () => {+ expect(Color(result.positive).hue()).toBeCloseTo(89, 0);+ });++ it("anchors negative at hue 359°", () => {+ const hue = Color(result.negative).hue();+ // 359 may round to 359 or wrap close to 0 depending on hex precision.+ expect(Math.min(Math.abs(hue - 359), Math.abs(hue + 1))).toBeLessThan(1);+ });++ it("places positive and negative at lightness 50", () => {+ expect(Color(result.positive).lightness()).toBeCloseTo(50, 0);+ expect(Color(result.negative).lightness()).toBeCloseTo(50, 0);+ });++ it("preserves brand saturation for positive and negative", () => {+ const brand = Color(BRAND);+ expect(+ Math.abs(Color(result.positive).saturationl() - brand.saturationl()),+ ).toBeLessThan(1);+ expect(+ Math.abs(Color(result.negative).saturationl() - brand.saturationl()),+ ).toBeLessThan(1);+ });+ });++ it("is deterministic for the same input", () => {+ expect(suggestHarmonyColors(BRAND)).toEqual(suggestHarmonyColors(BRAND));+ });+});