Skip to content

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

Integration branch for Embedding themes (#72147)

Phoomparin Mano7524d5d06270
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index ef1e20e8446..bd17345a57c 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -906,11 +906,13 @@
metabase.embedding.validation}
:uses #{analytics
api
+ models
premium-features
server
settings
util}
- :model-imports #{:model/Card :model/Dashboard}}
+ :model-imports #{:model/Card :model/Dashboard}
+ :model-exports #{:model/EmbeddingTheme}}
embedding-rest
{:team "Embedding"
@@ -930,7 +932,7 @@
request
tiles
util}
- :model-imports #{:model/Card :model/Dashboard}}
+ :model-imports #{:model/Card :model/Dashboard :model/EmbeddingTheme}}
events
{:team "DevEx"
diff --git a/e2e/test/scenarios/embedding/embedding-theme-editor/helpers/index.ts b/e2e/test/scenarios/embedding/embedding-theme-editor/helpers/index.ts
new file mode 100644
index 00000000000..8bbb53b1fc6
--- /dev/null
+++ b/e2e/test/scenarios/embedding/embedding-theme-editor/helpers/index.ts
@@ -0,0 +1,28 @@
+import { main } from "e2e/support/helpers";
+
+export function createThemeViaApi(name = "Test theme") {
+ return cy.request("POST", "/api/embed-theme", {
+ name,
+ settings: { colors: { brand: "#509EE3" } },
+ });
+}
+
+export function deleteAllThemes() {
+ cy.request("GET", "/api/embed-theme").then(({ body: themes }) => {
+ themes.forEach((theme: { id: number }) => {
+ cy.request("DELETE", `/api/embed-theme/${theme.id}`);
+ });
+ });
+}
+
+export const getThemeCard = (themeName: string) =>
+ main().findByText(themeName).parent();
+
+export function openThemeActionMenu(themeName: string) {
+ getThemeCard(themeName).findByLabelText("Duplicate and delete").click();
+}
+
+export function clickThemeMenuItem(themeName: string, menuItemLabel: string) {
+ openThemeActionMenu(themeName);
+ cy.findByRole("menuitem", { name: menuItemLabel }).click();
+}
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.ts
new file mode 100644
index 00000000000..b464a383a82
--- /dev/null
+++ b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-editor.cy.spec.ts
@@ -0,0 +1,429 @@
+const { H } = cy;
+
+function createThemeViaApi(name = "Test theme") {
+ return cy
+ .request("POST", "/api/embed-theme", {
+ name,
+ settings: {
+ colors: {
+ brand: "#509EE3",
+ background: "#ffffff",
+ "text-primary": "#2E353B",
+ "text-secondary": "#697D8C",
+ "text-tertiary": "#949AAB",
+ border: "#EEECEC",
+ "background-secondary": "#F9FBFC",
+ filter: "#7172AD",
+ summarize: "#88BF4D",
+ positive: "#84BB4C",
+ negative: "#ED6E6E",
+ shadow: "#000000",
+ charts: [
+ "#509EE3",
+ "#88BF4D",
+ "#A989C5",
+ "#EF8C8C",
+ "#F9D45C",
+ "#F2A86F",
+ "#98D9D9",
+ "#7172AD",
+ ],
+ },
+ fontFamily: "",
+ fontSize: "",
+ },
+ })
+ .then((response) => response.body);
+}
+
+function visitThemeEditor(themeId: number) {
+ cy.intercept("GET", `/api/embed-theme/${themeId}`).as("getTheme");
+ cy.visit(`/admin/embedding/themes/${themeId}`);
+ cy.wait("@getTheme");
+}
+
+function changeColor(label: string, value: string) {
+ H.main().within(() => {
+ cy.findByText(label).parent().parent().click();
+ });
+
+ H.popover().should("be.visible").find("input").first().clear().type(value);
+
+ cy.realPress("Escape");
+}
+
+describe(
+ "scenarios > embedding > themes > theme editor",
+ { tags: "@EE" },
+ () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ it("loads the theme editor page and shows the theme name", () => {
+ createThemeViaApi("My custom theme").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("editor panel should show the theme name");
+ cy.findByLabelText("Theme name").should("have.value", "My custom theme");
+
+ cy.log("sidebar should be hidden on theme editor page");
+ cy.findByTestId("admin-layout-sidebar").should("not.exist");
+
+ cy.log("save button should be disabled when no changes");
+ cy.findByRole("button", { name: /Save theme/ }).should("be.disabled");
+ });
+
+ it("can edit and save a theme name", () => {
+ createThemeViaApi("Original name").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("change the theme name");
+ cy.findByLabelText("Theme name").clear().type("Updated name");
+
+ cy.log("save button should be enabled");
+ cy.findByRole("button", { name: /Save theme/ }).should("be.enabled");
+
+ cy.log("save the theme");
+ cy.findByRole("button", { name: /Save theme/ }).click();
+
+ H.undoToast().findByText("Theme saved").should("exist");
+ });
+
+ it("can cancel and navigate back to listing", () => {
+ createThemeViaApi("A theme").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.findByRole("button", { name: /Cancel/ }).click();
+
+ cy.log("should navigate back to the themes listing");
+ cy.url().should("include", "/admin/embedding/themes");
+ cy.url().should("not.match", /\/themes\/\d+/);
+ });
+
+ it("shows not found for invalid theme id", () => {
+ cy.visit("/admin/embedding/themes/99999");
+
+ H.main().findByText("We're a little lost...").should("be.visible");
+ });
+
+ it("can delete the theme from the editor with confirmation", () => {
+ createThemeViaApi("Theme to delete").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("delete button should be visible");
+ cy.findByRole("button", { name: /Delete theme/ })
+ .scrollIntoView()
+ .should("be.visible");
+
+ cy.log("open the delete confirmation modal");
+ cy.findByRole("button", { name: /Delete theme/ }).click();
+
+ cy.findByRole("dialog").within(() => {
+ cy.findByText("Delete theme").should("be.visible");
+ cy.findByText(
+ "Are you sure you want to delete this theme? This action cannot be undone.",
+ ).should("be.visible");
+
+ cy.log("cancel the deletion");
+ cy.findByRole("button", { name: /Cancel/ }).click();
+ });
+
+ cy.log("should remain on the editor page after cancelling");
+ cy.url().should("match", /\/themes\/\d+/);
+
+ cy.log("confirm deletion");
+ cy.findByRole("button", { name: /Delete theme/ }).click();
+ cy.findByRole("dialog").within(() => {
+ cy.findByRole("button", { name: /Delete/ }).click();
+ });
+
+ H.undoToast().findByText("Theme deleted successfully").should("exist");
+
+ cy.log("should navigate back to the themes listing");
+ cy.url().should("include", "/admin/embedding/themes");
+ cy.url().should("not.match", /\/themes\/\d+/);
+
+ H.main().within(() => {
+ cy.findByText("Theme to delete").should("not.exist");
+ });
+ });
+
+ it("can delete a theme that has unsaved changes without getting stuck on a 404", () => {
+ // Repro of a bug where deleting a dirty theme would trigger the
+ // unsaved-changes guard. The redirect to the theme list got blocked,
+ // leaving the user on the now-deleted theme's URL — which 404s once
+ // the GET cache is invalidated.
+ createThemeViaApi("Dirty delete").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("dirty the editor by renaming the theme");
+ cy.findByLabelText("Theme name").clear().type("Renamed but unsaved");
+
+ cy.findByRole("button", { name: /Save theme/ }).should("be.enabled");
+
+ cy.log("delete the theme");
+ cy.findByRole("button", { name: /Delete theme/ }).click();
+ cy.findByRole("dialog").within(() => {
+ cy.findByRole("button", { name: /Delete/ }).click();
+ });
+
+ H.undoToast().findByText("Theme deleted successfully").should("exist");
+
+ cy.log("should land on the themes listing — not 404 or leave-prompt");
+ cy.url().should("include", "/admin/embedding/themes");
+ cy.url().should("not.match", /\/themes\/\d+/);
+ H.main().findByText("We're a little lost...").should("not.exist");
+ });
+
+ it("does not show the delete button when creating a new theme", () => {
+ cy.visit("/admin/embedding/themes/new");
+
+ cy.findByLabelText("Theme name").should("be.visible");
+ cy.findByRole("button", { name: /Delete theme/ }).should("not.exist");
+ });
+
+ describe("font settings", () => {
+ it("can edit font settings and save them", () => {
+ cy.intercept("PUT", "/api/embed-theme/*").as("updateTheme");
+
+ createThemeViaApi("Font test").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ H.main().within(() => {
+ cy.log("font fields should be visible");
+ cy.findByLabelText("Font").should("be.visible");
+ cy.findByLabelText("Base font size").should("be.visible");
+ });
+
+ cy.log("select a font family");
+ H.main().findByLabelText("Font").click();
+ cy.findByRole("option", { name: "Lato" }).click();
+
+ H.main().within(() => {
+ cy.log("set base font size");
+ cy.findByLabelText("Base font size").type("16");
+
+ cy.log("save the theme");
+ cy.findByRole("button", { name: /Save theme/ }).click();
+ });
+
+ cy.wait("@updateTheme").then((interception) => {
+ const { settings } = interception.request.body;
+ expect(settings.fontFamily).to.eq("Lato");
+ expect(settings.fontSize).to.eq("16px");
+ });
+
+ H.undoToast().findByText("Theme saved").should("exist");
+ });
+ });
+
+ describe("main colors", () => {
+ it("shows, edits, saves, and reverts main colors", () => {
+ cy.intercept("PUT", "/api/embed-theme/*").as("updateTheme");
+
+ createThemeViaApi("Main colors").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("main color swatches should be visible");
+ H.main().within(() => {
+ cy.findByText("Main colors").should("be.visible");
+ cy.findByText("Brand").should("be.visible");
+ cy.findByText("Background").should("be.visible");
+ cy.findByText("Primary text").should("be.visible");
+ });
+
+ cy.log("change the brand color");
+ changeColor("Brand", "FF0000");
+
+ cy.log("revert button should appear after changing a main color");
+ H.main()
+ .findByLabelText("Revert to default main colors")
+ .should("be.visible");
+
+ cy.log("click revert to reset main colors back to defaults");
+ H.main().findByLabelText("Revert to default main colors").click();
+
+ cy.log("revert button should disappear after resetting");
+ H.main()
+ .findByLabelText("Revert to default main colors")
+ .should("not.exist");
+
+ cy.log("change the brand color again");
+ changeColor("Brand", "FF0000");
+
+ cy.log("save the theme with the changed brand color");
+ cy.findByRole("button", { name: /Save theme/ }).click();
+
+ cy.wait("@updateTheme").then((interception) => {
+ const { settings } = interception.request.body;
+ expect(settings.colors?.brand).to.eq("#ff0000ff");
+ });
+
+ H.undoToast().findByText("Theme saved").should("exist");
+ });
+ });
+
+ describe("additional colors", () => {
+ it("shows additional colors section when expanded", () => {
+ createThemeViaApi("Colors test").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ H.main().within(() => {
+ cy.log("additional colors should be hidden by default");
+ cy.findByText("Secondary text").should("not.be.visible");
+
+ cy.log("expand additional colors");
+ cy.findByText("Show more colors").click();
+
+ cy.log("additional color rows should be visible");
+ cy.findByText("Secondary text").should("be.visible");
+ cy.findByText("Border").should("be.visible");
+ cy.findByText("Filter").should("be.visible");
+ cy.findByText("Chart colors").should("exist");
+
+ cy.log("collapse additional colors");
+ cy.findByText("Show fewer colors").click();
+ cy.findByText("Secondary text").should("not.be.visible");
+ });
+ });
+
+ it("can revert additional colors back to defaults", () => {
+ createThemeViaApi("Revert colors").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ H.main().within(() => {
+ cy.findByText("Show more colors").click();
+
+ cy.log(
+ "revert button should be visible since the API theme has non-default additional colors",
+ );
+ cy.findByLabelText("Revert to default additional colors").should(
+ "be.visible",
+ );
+
+ cy.log("click revert to reset additional colors to defaults");
+ cy.findByLabelText("Revert to default additional colors").click();
+
+ cy.log("revert button should disappear after resetting");
+ cy.findByLabelText("Revert to default additional colors").should(
+ "not.exist",
+ );
+ });
+ });
+
+ it("can edit additional colors and save them", () => {
+ cy.intercept("PUT", "/api/embed-theme/*").as("updateTheme");
+
+ createThemeViaApi("Edit colors").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ H.main().within(() => {
+ cy.findByText("Show more colors").click();
+ });
+
+ cy.log("edit the border color via its inline input");
+ changeColor("Border", "FF5733");
+
+ cy.log("edit the filter color via its inline input");
+ changeColor("Filter", "2D2D30");
+
+ cy.log("save the theme");
+ cy.findByRole("button", { name: /Save theme/ }).click();
+
+ cy.wait("@updateTheme").then((interception) => {
+ const { settings } = interception.request.body;
+ expect(settings.colors?.border).to.eq("#ff5733ff");
+ expect(settings.colors?.filter).to.eq("#2d2d30ff");
+ });
+
+ H.undoToast().findByText("Theme saved").should("exist");
+ });
+ });
+
+ describe("preview panel", () => {
+ it("shows enable embedding prompt when embedding is not enabled", () => {
+ H.updateSetting("enable-embedding-simple", false);
+
+ createThemeViaApi("Preview test").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("should show prompt to enable embedding");
+ H.main()
+ .findByText(
+ "Enable modular embedding to see a live preview of your theme.",
+ )
+ .should("be.visible");
+
+ H.main()
+ .findByRole("button", { name: /Enable modular embedding/ })
+ .should("be.visible");
+ });
+
+ it("shows theme preview when embedding is enabled", () => {
+ H.updateSetting("enable-embedding-simple", true);
+ H.updateSetting("show-simple-embed-terms", false);
+
+ createThemeViaApi("Preview test").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("should show the theme preview heading");
+ H.main().findByText("Theme preview").should("be.visible");
+ });
+ });
+
+ describe("preview picker", () => {
+ beforeEach(() => {
+ H.updateSetting("enable-embedding-simple", true);
+ H.updateSetting("show-simple-embed-terms", false);
+ });
+
+ it("defaults to a dashboard and can switch to a question", () => {
+ createThemeViaApi("Picker test").then((theme) => {
+ visitThemeEditor(theme.id);
+ });
+
+ cy.log("picker button shows the default dashboard name");
+ H.main()
+ .findByLabelText("Change preview resource")
+ .should("be.visible")
+ .and("contain", "Orders in a dashboard");
+
+ cy.log("preview renders the dashboard web component");
+ H.main().find("metabase-dashboard").should("exist");
+
+ cy.log("opens the entity picker modal");
+ H.main().findByLabelText("Change preview resource").click();
+
+ H.entityPickerModal().within(() => {
+ cy.findByText("Select data to preview").should("be.visible");
+ cy.findByText("Our analytics").click();
+ cy.findByText("Orders, Count").click();
+ });
+
+ cy.log("picker button updates to the selected question");
+ H.main()
+ .findByLabelText("Change preview resource")
+ .should("contain", "Orders, Count");
+
+ cy.log("preview switches to the question web component");
+ H.main().find("metabase-question").should("exist");
+ H.main().find("metabase-dashboard").should("not.exist");
+ });
+ });
+ },
+);
diff --git a/e2e/test/scenarios/embedding/embedding-theme-editor/theme-listing.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-listing.cy.spec.ts
new file mode 100644
index 00000000000..e9dbcb14a20
--- /dev/null
+++ b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-listing.cy.spec.ts
@@ -0,0 +1,192 @@
+const { H } = cy;
+
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+
+import {
+ clickThemeMenuItem,
+ createThemeViaApi,
+ deleteAllThemes,
+ openThemeActionMenu,
+} from "./helpers";
+
+describe(
+ "scenarios > embedding > themes > theme listing",
+ { tags: "@EE" },
+ () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ it("lazily seeds Light and Dark on first visit, and preserves admin deletions across reloads", () => {
+ cy.visit("/admin/embedding/themes");
+
+ H.main().within(() => {
+ cy.log(
+ "default Light and Dark themes are seeded lazily on first visit",
+ );
+ cy.findByText("Light").should("be.visible");
+ cy.findByText("Dark").should("be.visible");
+
+ cy.log("new theme card is visible");
+ cy.findByRole("button", { name: /New theme/ }).should("be.visible");
+ });
+
+ cy.log("admin deletes the seeded defaults");
+ deleteAllThemes();
+ cy.reload();
+
+ H.main().within(() => {
+ cy.log("empty state is shown; defaults are not re-created");
+ cy.findByText("Light").should("not.exist");
+ cy.findByText("Dark").should("not.exist");
+
+ cy.log("clicking New theme navigates to the draft editor");
+ cy.findByRole("button", { name: /New theme/ }).click();
+ });
+
+ cy.url().should("match", /\/admin\/embedding\/themes\/new$/);
+ });
+
+ it("does not create a theme when cancelling from the draft editor", () => {
+ cy.intercept("POST", "/api/embed-theme").as("createTheme");
+ cy.visit("/admin/embedding/themes");
+
+ H.main()
+ .findByRole("button", { name: /New theme/ })
+ .click();
+
+ cy.url().should("match", /\/admin\/embedding\/themes\/new$/);
+
+ cy.findByRole("button", { name: /Cancel/ }).click();
+
+ cy.log("navigates back to the listing");
+ cy.url().should("match", /\/admin\/embedding\/themes$/);
+
+ cy.log("new theme card is still visible");
+ H.main()
+ .findByRole("button", { name: /New theme/ })
+ .should("be.visible");
+
+ cy.log("no POST was issued");
+ cy.get("@createTheme.all").should("have.length", 0);
+ });
+
+ it("navigates to theme editor when clicking an existing theme card", () => {
+ createThemeViaApi("My theme");
+ cy.visit("/admin/embedding/themes");
+
+ H.main().within(() => {
+ cy.findByText("My theme").click();
+ });
+
+ cy.log("navigates to the theme editor page");
+ cy.url().should("match", /\/admin\/embedding\/themes\/\d+/);
+ });
+
+ it("uses white-labeled colors as a base for creating themes", () => {
+ const whitelabelColors = {
+ brand: "#8e44ad",
+ filter: "#16a085",
+ summarize: "#d35400",
+ accent0: "#e74c3c",
+ accent7: "#34495e",
+ };
+
+ // @ts-expect-error -- the utility is not aware of enterprise settings
+ H.updateSetting("application-colors", whitelabelColors);
+
+ cy.intercept("POST", "/api/embed-theme").as("createTheme");
+ cy.visit("/admin/embedding/themes");
+
+ H.main()
+ .findByRole("button", { name: /New theme/ })
+ .click();
+
+ cy.findByRole("button", { name: /Save theme/ }).click();
+
+ cy.wait<{ name: string; settings: MetabaseTheme }>("@createTheme").then(
+ (interception) => {
+ const { name, settings } = interception.request.body;
+
+ expect(name).to.eq("Untitled theme");
+
+ // We capture a snapshot of the current white-labeled colors when creating themes.
+ // The internal BI's whitelabeled colors may be different from the embedding colors,
+ // so this white-labeled color will stay the same as the appearance settings changes.
+ expect(settings.colors?.brand).to.eq(whitelabelColors.brand);
+ expect(settings.colors?.filter).to.eq(whitelabelColors.filter);
+ expect(settings.colors?.summarize).to.eq(whitelabelColors.summarize);
+ expect(settings.colors?.charts?.[0]).to.eq(whitelabelColors.accent0);
+ expect(settings.colors?.charts?.[7]).to.eq(whitelabelColors.accent7);
+ },
+ );
+ });
+
+ it("can duplicate a theme", () => {
+ createThemeViaApi("Untitled theme");
+ cy.visit("/admin/embedding/themes");
+
+ H.main().within(() => {
+ cy.findByText("Untitled theme").should("be.visible");
+ });
+
+ cy.log("duplicate a theme");
+ clickThemeMenuItem("Untitled theme", "Duplicate");
+
+ H.undoToast().findByText("Theme duplicated successfully").should("exist");
+
+ H.main().within(() => {
+ cy.log("duplicated theme should have 'Copy of' prepended");
+ cy.findByText("Untitled theme").scrollIntoView().should("be.visible");
+ cy.findByText("Copy of Untitled theme").should("be.visible");
+ });
+ });
+
+ it("can delete a theme with confirmation", () => {
+ createThemeViaApi("Untitled theme");
+ cy.visit("/admin/embedding/themes");
+
+ H.main().findByText("Untitled theme").should("be.visible");
+
+ cy.log("delete a theme");
+ clickThemeMenuItem("Untitled theme", "Delete");
+
+ cy.log("delete confirmation modal should appear");
+ cy.findByRole("dialog").within(() => {
+ cy.findByText("Delete theme").should("be.visible");
+
+ cy.findByText(
+ "Are you sure you want to delete this theme? This action cannot be undone.",
+ ).should("be.visible");
+
+ cy.log("cancel the deletion");
+ cy.findByRole("button", { name: /Cancel/ }).click();
+ });
+
+ cy.log("theme should still exist");
+ H.main().findByText("Untitled theme").should("be.visible");
+
+ openThemeActionMenu("Untitled theme");
+
+ cy.log("confirm deletion");
+ cy.findByRole("menuitem", { name: /Delete/ }).click();
+ cy.findByRole("dialog").within(() => {
+ cy.findByRole("button", { name: /Delete/ }).click();
+ });
+
+ H.undoToast().findByText("Theme deleted successfully").should("exist");
+
+ H.main().within(() => {
+ cy.log(
+ "deleted theme is gone; default themes and new theme card remain",
+ );
+ cy.findByText("Untitled theme").should("not.exist");
+ cy.findByText("Light").should("be.visible");
+ cy.findByText("Dark").should("be.visible");
+ cy.findByRole("button", { name: /New theme/ }).should("be.visible");
+ });
+ });
+ },
+);
diff --git a/e2e/test/scenarios/embedding/embedding-theme-editor/theme-upsell.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-upsell.cy.spec.ts
new file mode 100644
index 00000000000..c2fb00c2d4f
--- /dev/null
+++ b/e2e/test/scenarios/embedding/embedding-theme-editor/theme-upsell.cy.spec.ts
@@ -0,0 +1,195 @@
+const { H } = cy;
+
+describe("scenarios > embedding > themes > upsell", () => {
+ describe("OSS", { tags: "@OSS" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("shows the upsell with Metabase Pro copy and an external upgrade link", () => {
+ cy.visit("/admin/embedding/themes");
+
+ cy.log("nav label has an upsell gem");
+ cy.findByTestId("admin-layout-sidebar")
+ .findByRole("link", { name: /Themes/ })
+ .within(() => {
+ cy.icon("gem").should("be.visible");
+ });
+
+ H.main().within(() => {
+ cy.log("upsell copy matches the Figma");
+ cy.findByText("Metabase Pro").should("be.visible");
+ cy.findByRole("heading", { name: "Create custom themes" }).should(
+ "be.visible",
+ );
+ cy.findByText(
+ "Fine-tune the appearance of your embedded content with colors and fonts.",
+ ).should("be.visible");
+
+ cy.log("CTA is an external upgrade link for non-hosted instances");
+ cy.findByRole("link", { name: "Upgrade to Pro" })
+ .should("be.visible")
+ .and("have.attr", "href")
+ .and("include", "utm_campaign=embedding-themes")
+ .and("include", "source_plan=oss");
+
+ cy.log("theme listing controls are not rendered");
+ cy.findByRole("button", { name: /New theme/ }).should("not.exist");
+ });
+ });
+ });
+
+ describe("Starter", { tags: "@EE" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("starter");
+ });
+
+ it("shows the upsell with a Store Admin contact message instead of a CTA", () => {
+ cy.visit("/admin/embedding/themes");
+
+ cy.log("nav label has an upsell gem");
+ cy.findByTestId("admin-layout-sidebar")
+ .findByRole("link", { name: /Themes/ })
+ .within(() => {
+ cy.icon("gem").should("be.visible");
+ });
+
+ H.main().within(() => {
+ cy.findByText("Metabase Pro").should("be.visible");
+ cy.findByRole("heading", { name: "Create custom themes" }).should(
+ "be.visible",
+ );
+ cy.findByText(
+ "Fine-tune the appearance of your embedded content with colors and fonts.",
+ ).should("be.visible");
+
+ cy.log(
+ "hosted, non-Store-Admin users see the contact-admin message instead of a CTA",
+ );
+ cy.findByText(
+ /Please ask a Metabase Store Admin.*to upgrade your plan\./,
+ ).should("be.visible");
+ cy.findByRole("button", { name: "Upgrade to Pro" }).should("not.exist");
+ cy.findByRole("link", { name: "Upgrade to Pro" }).should("not.exist");
+
+ cy.findByRole("button", { name: /New theme/ }).should("not.exist");
+ });
+ });
+
+ it("shows the Upgrade to Pro CTA when the current admin is a Metabase Store Admin", () => {
+ cy.log(
+ "inject the current admin into token-status.store-users so isStoreUser becomes true",
+ );
+ cy.intercept("GET", "/api/session/properties", (req) => {
+ req.continue((res) => {
+ res.body["token-status"] = {
+ ...(res.body["token-status"] ?? {}),
+ "store-users": [{ email: "[email protected]" }],
+ };
+ res.send();
+ });
+ });
+
+ cy.log(
+ "keep the trial check deterministic — no trial, so CTA stays 'Upgrade to Pro'",
+ );
+ cy.intercept("POST", "/api/ee/cloud-proxy/mb-plan-trial-up-available", {
+ body: { available: false, plan_alias: "pro-cloud" },
+ });
+
+ cy.visit("/admin/embedding/themes");
+
+ H.main().within(() => {
+ cy.findByText("Metabase Pro").should("be.visible");
+ cy.findByRole("heading", { name: "Create custom themes" }).should(
+ "be.visible",
+ );
+
+ cy.log("contact-admin fallback is not rendered");
+ cy.findByText(/Please ask a Metabase Store Admin/).should("not.exist");
+
+ cy.log("no trial → no trial line");
+ cy.findByText(/14-day free trial/).should("not.exist");
+
+ cy.log(
+ "CTA is rendered (hosted starter as store admin → opens the upgrade modal)",
+ );
+ cy.findByRole("button", { name: "Upgrade to Pro" }).should(
+ "be.visible",
+ );
+ });
+ });
+
+ it("shows the Try for free CTA and trial copy when a trial is available", () => {
+ cy.log("admin is a Store Admin, so the CTA branch is taken");
+ cy.intercept("GET", "/api/session/properties", (req) => {
+ req.continue((res) => {
+ res.body["token-status"] = {
+ ...(res.body["token-status"] ?? {}),
+ "store-users": [{ email: "[email protected]" }],
+ };
+ res.send();
+ });
+ });
+
+ cy.log(
+ "trial is available → CTA switches to 'Try for free' and trial line appears",
+ );
+ cy.intercept("POST", "/api/ee/cloud-proxy/mb-plan-trial-up-available", {
+ body: { available: true, plan_alias: "pro-cloud" },
+ });
+
+ cy.visit("/admin/embedding/themes");
+
+ H.main().within(() => {
+ cy.findByText("Metabase Pro").should("be.visible");
+ cy.findByRole("heading", { name: "Create custom themes" }).should(
+ "be.visible",
+ );
+
+ cy.log("trial line is rendered");
+ cy.findByText(
+ /Get a 14-day free trial of this and other pro features/,
+ ).should("be.visible");
+
+ cy.log("button text switches to 'Try for free'");
+ cy.findByRole("button", { name: "Try for free" }).should("be.visible");
+ cy.findByRole("button", { name: "Upgrade to Pro" }).should("not.exist");
+ });
+ });
+ });
+
+ describe("Pro", { tags: "@EE" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ it("does not show the upsell and renders the themes listing", () => {
+ cy.visit("/admin/embedding/themes");
+
+ cy.log("nav label has no upsell gem");
+ cy.findByTestId("admin-layout-sidebar")
+ .findByRole("link", { name: /Themes/ })
+ .within(() => {
+ cy.icon("gem").should("not.exist");
+ });
+
+ H.main().within(() => {
+ cy.log("upsell copy is absent");
+ cy.findByText("Metabase Pro").should("not.exist");
+ cy.findByRole("heading", { name: "Create custom themes" }).should(
+ "not.exist",
+ );
+
+ cy.log("theme listing is rendered");
+ cy.findByRole("heading", { name: "Themes" }).should("be.visible");
+ cy.findByRole("button", { name: /New theme/ }).should("be.visible");
+ });
+ });
+ });
+});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
index 356ad7a6915..9ddcb654a3e 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
@@ -821,6 +821,9 @@ describe(suiteTitle, () => {
cy.button("Unpublish").should("be.visible");
+ cy.log("Selecting custom colors");
+ cy.findByTestId("theme-card-Custom").click();
+
cy.log("brand color should be visible");
getEmbedSidebar().within(() => {
cy.findByText("Brand color").should("be.visible");
@@ -902,6 +905,9 @@ describe(suiteTitle, () => {
preselectSso: true,
});
+ cy.log("Selecting custom colors");
+ cy.findByTestId("theme-card-Custom").click();
+
cy.log("click on brand color picker");
cy.findByTestId("brand-color-picker").findByRole("button").click();
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
index 8c5500f9e6b..851f3781afc 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/user-settings-persistence.cy.spec.ts
@@ -22,6 +22,9 @@ describe("scenarios > embedding > sdk iframe embed setup > user settings persist
resourceName: DASHBOARD_NAME,
});
+ cy.log("0. select custom colors");
+ cy.findByTestId("theme-card-Custom").click();
+
cy.log("1. change brand color to red");
cy.findByTestId("brand-color-picker").findByRole("button").click();
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj
index bd7ef17d339..7e186cec2b6 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj
@@ -35,7 +35,10 @@
(conj "Setting")
(not (:no-transforms opts))
- (conj "Transform" "TransformTag" "TransformJob" "PythonLibrary")))
+ (conj "Transform" "TransformTag" "TransformJob" "PythonLibrary")
+
+ (not (:no-embedding-themes opts))
+ (conj "EmbeddingTheme")))
(defn make-targets-of-type
"Returns a targets seq with model type and given ids"
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj
index 48aa5a0caa5..222795dc6cd 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj
@@ -82,7 +82,7 @@
(def legal-top-level-paths
"Known top-level paths for directory with serialization output.
We support both \"python-libraries\" and \"python_libraries\" for backwards compatibility. The modern name is \"python_libraries\"."
- #{"actions" "channels" "collections" "databases" "glossary" "metabots" "python_libraries" "python-libraries" "snippets" "transforms"})
+ #{"actions" "channels" "collections" "databases" "embedding_themes" "glossary" "metabots" "python_libraries" "python-libraries" "snippets" "transforms"})
(defn- ingest-all
"Returns {:entities {unlabeled-hierarchy [hierarchy File]}, :errors [Exception...]}.
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index f04b4f2e55c..5814d3b2e81 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -33,7 +33,8 @@
"The list of all models exported by serialization by default. Used for production code and by tests."
(concat data-model
content
- ["FieldValues"
+ ["EmbeddingTheme"
+ "FieldValues"
"Metabot"
"PythonLibrary"
"Setting"
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
index 4eac8dad945..2598310283c 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
@@ -2776,3 +2776,35 @@
(let [ser (ts/extract-one "Channel" http-id)]
(is (= [{:label "channels"} {:label "HTTP Channel" :key "HTTP Channel"}]
(serdes/storage-path ser {}))))))))
+
+(deftest embedding-theme-test
+ (mt/with-empty-h2-app-db!
+ (ts/with-temp-dpc [:model/EmbeddingTheme
+ {light-id :id
+ light-eid :entity_id}
+ {:name "Light"
+ :settings {}}
+
+ :model/EmbeddingTheme
+ {_dark-id :id
+ dark-eid :entity_id}
+ {:name "Dark"
+ :settings {}}]
+ (testing "embedding theme extracts correctly"
+ (let [ser (serdes/extract-one "EmbeddingTheme" {} (t2/select-one :model/EmbeddingTheme :id light-id))]
+ (is (=? {:serdes/meta [{:model "EmbeddingTheme"
+ :id light-eid
+ :label "light"}]
+ :entity_id light-eid
+ :name "Light"
+ :settings {}
+ :created_at string?
+ :updated_at string?}
+ ser))
+ (is (not (contains? ser :id)))
+ (testing "embedding themes have no dependencies"
+ (is (empty? (serdes/dependencies ser))))))
+
+ (testing "all embedding themes are extracted"
+ (is (= #{light-eid dark-eid}
+ (ids-by-model "EmbeddingTheme" (extract/extract {}))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/upsells/pages/TransformsUpsellPage/TransformsUpsellPage.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/upsells/pages/TransformsUpsellPage/TransformsUpsellPage.tsx
index a5a2053a455..45555bd9a18 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms/upsells/pages/TransformsUpsellPage/TransformsUpsellPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms/upsells/pages/TransformsUpsellPage/TransformsUpsellPage.tsx
@@ -3,10 +3,10 @@ import { useCallback, useState } from "react";
import { jt, t } from "ttag";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { DottedBackground } from "metabase/common/components/upsells/components/DottedBackground";
+import { LineDecorator } from "metabase/common/components/upsells/components/LineDecorator";
import { DataStudioBreadcrumbs } from "metabase/data-studio/common/components/DataStudioBreadcrumbs";
import { PaneHeader } from "metabase/data-studio/common/components/PaneHeader";
-import { DottedBackground } from "metabase/data-studio/upsells/components/DottedBackground";
-import { LineDecorator } from "metabase/data-studio/upsells/components/LineDecorator";
import { useMetadataToasts } from "metabase/metadata/hooks/useMetadataToasts";
import { useSelector } from "metabase/redux";
import { getStoreUsers } from "metabase/selectors/store-users";
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorPreview/utils.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorPreview/utils.ts
index 1832a15b5b8..c87bcaaf8ba 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorPreview/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorPreview/utils.ts
@@ -1,12 +1,17 @@
import _ from "underscore";
import { color } from "metabase/ui/colors";
+import { ACCENT_COUNT } from "metabase/ui/colors/palette";
export const getAccentColorGroups = (palette: Record<string, string>) => {
const groups = [
- _.times(8, (i) => [`accent${i}`]),
- _.times(8, (i) => [`accent${i}`, `accent${i}-dark`]),
- _.times(8, (i) => [`accent${i}`, `accent${i}-light`, `accent${i}-dark`]),
+ _.times(ACCENT_COUNT, (i) => [`accent${i}`]),
+ _.times(ACCENT_COUNT, (i) => [`accent${i}`, `accent${i}-dark`]),
+ _.times(ACCENT_COUNT, (i) => [
+ `accent${i}`,
+ `accent${i}-light`,
+ `accent${i}-dark`,
+ ]),
];
return groups.map((group) =>
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorSettings/utils.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorSettings/utils.ts
index bfd07d210f4..423d8108bfe 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorSettings/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/ChartColorSettings/utils.ts
@@ -2,8 +2,10 @@ import type { ColorInstance } from "color";
import Color from "color";
import _ from "underscore";
+import { ACCENT_COUNT } from "metabase/ui/colors/palette";
+
export const getChartColorGroups = (): string[][] => {
- return _.times(8, (i) => [
+ return _.times(ACCENT_COUNT, (i) => [
`accent${i}`,
`accent${i}-light`,
`accent${i}-dark`,
diff --git a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
index 1bed6d819a8..c0df35f8650 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
@@ -111,9 +111,7 @@ export const ComponentProviderInternal = (
}, [reduxStore, isGuestEmbed]);
useEffect(() => {
- if (fontFamily) {
- reduxStore.dispatch(setOptions({ font: fontFamily }));
- }
+ reduxStore.dispatch(setOptions({ font: fontFamily }));
}, [reduxStore, fontFamily]);
useEffect(() => {
diff --git a/frontend/src/metabase-types/api/embedding-theme.ts b/frontend/src/metabase-types/api/embedding-theme.ts
new file mode 100644
index 00000000000..ebe4fea15e7
--- /dev/null
+++ b/frontend/src/metabase-types/api/embedding-theme.ts
@@ -0,0 +1,24 @@
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+
+export interface EmbeddingTheme {
+ id: number;
+ name: string;
+ settings: MetabaseTheme;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface CreateEmbeddingThemeRequest {
+ name: string;
+ settings: MetabaseTheme;
+}
+
+export interface UpdateEmbeddingThemeRequest {
+ id: number;
+ name?: string;
+ settings?: MetabaseTheme;
+}
+
+export interface SeedDefaultEmbeddingThemesRequest {
+ themes: CreateEmbeddingThemeRequest[];
+}
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 1efb2be176c..c12ebd305b8 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -19,6 +19,7 @@ export * from "./dataset";
export * from "./dependencies";
export * from "./document";
export * from "./email";
+export * from "./embedding-theme";
export * from "./entity-id";
export * from "./field";
export * from "./metric";
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index 04358b574b6..ec2822bad16 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -420,6 +420,7 @@ export const createMockSettings = (
"embedding-hub-test-embed-snippet-created": false,
"embedding-hub-production-embed-snippet-created": false,
"embedding-hub-sso-auth-manual-tested": false,
+ "default-embedding-themes-seeded": true,
"notebook-native-preview-sidebar-width": null,
"query-analysis-enabled": false,
"check-for-updates": true,
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index 7c24f629798..ebea977e590 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -510,6 +510,7 @@ interface AdminSettings {
"embedding-hub-test-embed-snippet-created": boolean;
"embedding-hub-production-embed-snippet-created": boolean;
"embedding-hub-sso-auth-manual-tested": boolean;
+ "default-embedding-themes-seeded": boolean;
"security-center-email-recipients": NotificationRecipient[] | null;
"security-center-slack-channel": string | null;
"store-url": string;
@@ -779,6 +780,7 @@ export interface EnterpriseSettings extends Settings {
"embedding-hub-test-embed-snippet-created": boolean;
"embedding-hub-production-embed-snippet-created": boolean;
"embedding-hub-sso-auth-manual-tested": boolean;
+ "default-embedding-themes-seeded": boolean;
"python-runner-url"?: string | null;
"python-runner-api-token"?: string | null;
"python-storage-s-3-endpoint"?: string | null;
diff --git a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
index 141a174b79c..d2600e11d0a 100644
--- a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
+++ b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
@@ -5,6 +5,7 @@ import {
type AdminNavItemProps,
AdminNavWrapper,
} from "metabase/admin/components/AdminNav";
+import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { useHasTokenFeature } from "metabase/common/hooks";
import { useSelector } from "metabase/redux";
import { getLocation } from "metabase/selectors/routing";
@@ -52,6 +53,17 @@ export function EmbeddingNav() {
label={t`Security`}
icon="shield_outline"
/>
+
+ <EmbeddingNavItem
+ path="/admin/embedding/themes"
+ label={
+ <Flex gap="sm" align="center">
+ <span>{t`Themes`}</span>
+ {!hasSimpleEmbedding && <UpsellGem />}
+ </Flex>
+ }
+ icon="palette"
+ />
</Stack>
</AdminNavWrapper>
);
diff --git a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx
new file mode 100644
index 00000000000..44c7652fe5f
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx
@@ -0,0 +1,60 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen, within } from "__support__/ui";
+import {
+ createMockLocation,
+ createMockRoutingState,
+ createMockSettingsState,
+} from "metabase/redux/store/mocks";
+import {
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { EmbeddingNav } from "./EmbeddingNav";
+
+const setup = ({
+ hasSimpleEmbedding = false,
+}: {
+ hasSimpleEmbedding?: boolean;
+} = {}) => {
+ const initialRoute = "/admin/embedding/themes";
+ const settings = createMockSettings({
+ "token-features": createMockTokenFeatures({
+ embedding_simple: hasSimpleEmbedding,
+ }),
+ });
+
+ renderWithProviders(<Route path="*" component={EmbeddingNav} />, {
+ withRouter: true,
+ initialRoute,
+ storeInitialState: {
+ currentUser: createMockUser({ is_superuser: true }),
+ routing: createMockRoutingState({
+ locationBeforeTransitions: createMockLocation({
+ pathname: initialRoute,
+ }),
+ }),
+ settings: createMockSettingsState(settings),
+ },
+ });
+};
+
+describe("EmbeddingNav", () => {
+ it("shows an upsell gem next to the Themes label for OSS/starter users", () => {
+ setup({ hasSimpleEmbedding: false });
+
+ const themesLink = screen.getByRole("link", { name: /Themes/ });
+ expect(within(themesLink).getByTestId("upsell-gem")).toBeInTheDocument();
+ });
+
+ it("does not show an upsell gem next to the Themes label for Pro users", () => {
+ setup({ hasSimpleEmbedding: true });
+
+ const themesLink = screen.getByRole("link", { name: /Themes/ });
+ expect(
+ within(themesLink).queryByTestId("upsell-gem"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorRow.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorRow.tsx
new file mode 100644
index 00000000000..4690a509d55
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorRow.tsx
@@ -0,0 +1,17 @@
+import { ColorPicker } from "metabase/common/components/ColorPicker";
+import { Flex, Text } from "metabase/ui";
+
+interface ColorRowProps {
+ label: string;
+ value: string;
+ onChange: (color?: string) => void;
+}
+
+export function ColorRow({ label, value, onChange }: ColorRowProps) {
+ return (
+ <Flex align="center" justify="space-between">
+ <Text fz="sm">{label}</Text>
+ <ColorPicker value={value} onChange={onChange} />
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorSwatchCard.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorSwatchCard.tsx
new file mode 100644
index 00000000000..1fc23fea893
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ColorSwatchCard.tsx
@@ -0,0 +1,50 @@
+import { ColorPickerContent } from "metabase/common/components/ColorPicker/ColorPickerContent";
+import { Box, Card, Flex, Popover, Text } from "metabase/ui";
+
+interface ColorSwatchCardProps {
+ label: string;
+ value: string;
+ showAlpha?: boolean;
+ onChange: (color?: string) => void;
+}
+
+export function ColorSwatchCard({
+ label,
+ value,
+ showAlpha,
+ onChange,
+}: ColorSwatchCardProps) {
+ return (
+ <Popover position="bottom" shadow="md">
+ <Popover.Target>
+ <Card withBorder p="sm" style={{ cursor: "pointer", flex: 1 }}>
+ <Flex
+ h={48}
+ direction="column"
+ align="center"
+ justify="space-evenly"
+ pt={3}
+ >
+ <Box
+ w={20}
+ h={20}
+ style={{
+ borderRadius: "50%",
+ backgroundColor: value || "transparent",
+ border: "1px solid var(--mb-color-border)",
+ }}
+ />
+ <Text fz={10}>{label}</Text>
+ </Flex>
+ </Card>
+ </Popover.Target>
+ <Popover.Dropdown>
+ <ColorPickerContent
+ value={value}
+ showAlpha={showAlpha}
+ onChange={onChange}
+ />
+ </Popover.Dropdown>
+ </Popover>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx
new file mode 100644
index 00000000000..435cdef268b
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EditorPanel.tsx
@@ -0,0 +1,274 @@
+import { useMemo, useState } from "react";
+import { t } from "ttag";
+
+import type { EmbeddingThemeEditorResult } from "metabase/admin/embedding/hooks/use-embedding-theme-editor";
+import type { MetabaseFontFamily } from "metabase/embedding-sdk/theme/fonts";
+import {
+ Box,
+ Button,
+ Card,
+ Collapse,
+ CopyButton,
+ Flex,
+ Icon,
+ Select,
+ Stack,
+ Text,
+ TextInput,
+ UnstyledButton,
+} from "metabase/ui";
+
+import { ColorSwatchCard } from "./ColorSwatchCard";
+import {
+ CHART_COLOR_COUNT,
+ FONT_FAMILY_OPTIONS,
+ MORE_COLORS,
+ PRIMARY_COLORS,
+} from "./constants";
+import { getThemeCodeSnippet } from "./get-theme-code-snippet";
+
+interface EditorPanelProps {
+ editor: EmbeddingThemeEditorResult;
+ onSave: () => void;
+ onCancel: () => void;
+ onDelete?: () => void;
+}
+
+export function EditorPanel({
+ editor,
+ onSave,
+ onCancel,
+ onDelete,
+}: EditorPanelProps) {
+ const [moreColorsOpen, setMoreColorsOpen] = useState(false);
+
+ const { currentTheme } = editor;
+ const themeCodeSnippet = useMemo(
+ () => getThemeCodeSnippet(currentTheme?.settings ?? {}),
+ [currentTheme?.settings],
+ );
+
+ if (!currentTheme) {
+ return null;
+ }
+
+ const colors = currentTheme.settings.colors ?? {};
+ const charts = colors.charts ?? [];
+
+ const parseFontSizeNumber = (fontSize: string | undefined): string => {
+ if (!fontSize) {
+ return "";
+ }
+ const num = parseFloat(fontSize);
+ return isNaN(num) ? "" : String(num);
+ };
+
+ return (
+ <Flex
+ direction="column"
+ w="100%"
+ maw={480}
+ style={{ borderRight: "1px solid var(--mb-color-border)" }}
+ >
+ <Box flex={1} style={{ overflow: "auto" }} p="xl">
+ <Flex align="center" justify="space-between" mb="xl">
+ <Text fw={700} fz="xl">{t`Edit theme`}</Text>
+ <CopyButton value={themeCodeSnippet}>
+ {({ copied, copy }) => (
+ <Button
+ variant="subtle"
+ size="compact-sm"
+ leftSection={<Icon name="copy" size={16} />}
+ onClick={copy}
+ >
+ {copied ? t`Copied!` : t`Copy code`}
+ </Button>
+ )}
+ </CopyButton>
+ </Flex>
+
+ <Stack gap="lg">
+ {/* Theme name */}
+ <Card withBorder p="lg">
+ <TextInput
+ label={t`Theme name`}
+ value={currentTheme.name}
+ onChange={(e) => editor.setName(e.currentTarget.value)}
+ autoFocus
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ </Card>
+
+ {/* Main colors */}
+ <Card withBorder p="lg">
+ <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>
+ )}
+ </Flex>
+ <Flex gap="sm">
+ {PRIMARY_COLORS.map(({ key, label }) => (
+ <ColorSwatchCard
+ key={key}
+ label={label()}
+ value={(colors[key] as string) ?? ""}
+ showAlpha
+ onChange={(color) => editor.setColor(key, color ?? "")}
+ />
+ ))}
+ </Flex>
+
+ <Flex mt="md" h="26" align="center" justify="space-between">
+ <UnstyledButton onClick={() => setMoreColorsOpen((v) => !v)}>
+ <Flex align="center" gap="xs">
+ <Text c="brand" fz="sm" fw={600}>
+ {moreColorsOpen
+ ? t`Show fewer colors`
+ : t`Show more colors`}
+ </Text>
+ <Icon
+ name={moreColorsOpen ? "chevronup" : "chevronright"}
+ size={12}
+ c="brand"
+ />
+ </Flex>
+ </UnstyledButton>
+
+ {editor.hasAdditionalColorChanges && (
+ <Button
+ variant="subtle"
+ size="compact-sm"
+ aria-label={t`Revert to default additional colors`}
+ onClick={editor.resetAdditionalColors}
+ >
+ <Icon name="revert" size={16} />
+ </Button>
+ )}
+ </Flex>
+
+ <Collapse in={moreColorsOpen}>
+ <Box
+ mt="sm"
+ style={{
+ display: "grid",
+ gridTemplateColumns: "repeat(3, 1fr)",
+ gap: "var(--mantine-spacing-sm)",
+ }}
+ >
+ {MORE_COLORS.map(({ key, label }) => (
+ <ColorSwatchCard
+ key={key}
+ label={label()}
+ value={(colors[key] as string) ?? ""}
+ showAlpha
+ onChange={(color) => editor.setColor(key, color ?? "")}
+ />
+ ))}
+ </Box>
+
+ <Text fw={600} fz="sm" mt="sm">{t`Chart colors`}</Text>
+ <Box
+ mt="sm"
+ style={{
+ display: "grid",
+ gridTemplateColumns: "repeat(3, 1fr)",
+ gap: "var(--mantine-spacing-sm)",
+ }}
+ >
+ {Array.from({ length: CHART_COLOR_COUNT }, (_, i) => {
+ const chartColor = charts[i];
+ const value =
+ typeof chartColor === "object" && chartColor?.base
+ ? chartColor.base
+ : typeof chartColor === "string"
+ ? chartColor
+ : "";
+ return (
+ <ColorSwatchCard
+ key={i}
+ label={`Chart ${i + 1}`}
+ value={value}
+ showAlpha
+ onChange={(color) => editor.setChartColor(i, color ?? "")}
+ />
+ );
+ })}
+ </Box>
+ </Collapse>
+ </Card>
+
+ {/* Font */}
+ <Card withBorder p="lg">
+ <Stack gap="md">
+ <Select
+ label={t`Font`}
+ data={FONT_FAMILY_OPTIONS}
+ value={currentTheme.settings.fontFamily ?? ""}
+ onChange={(value) =>
+ editor.setFontFamily((value ?? "") as MetabaseFontFamily)
+ }
+ placeholder={t`Default`}
+ clearable
+ searchable
+ />
+ <TextInput
+ label={t`Base font size`}
+ value={parseFontSizeNumber(currentTheme.settings.fontSize)}
+ onChange={(e) => {
+ const raw = e.currentTarget.value;
+ if (raw !== "" && !/^\d+$/.test(raw)) {
+ return;
+ }
+ editor.setFontSize(raw ? `${raw}px` : "");
+ }}
+ placeholder={t`Default`}
+ rightSection={
+ <Text c="text-tertiary" fz="sm">
+ {"px"}
+ </Text>
+ }
+ />
+ </Stack>
+ </Card>
+ </Stack>
+
+ {onDelete && (
+ <Button
+ mt="lg"
+ variant="subtle"
+ color="error"
+ px={0}
+ leftSection={<Icon name="trash" size={16} />}
+ onClick={onDelete}
+ >
+ {t`Delete theme`}
+ </Button>
+ )}
+ </Box>
+
+ {/* Bottom action bar */}
+ <Flex
+ p="lg"
+ gap="md"
+ justify="space-between"
+ style={{ borderTop: "1px solid var(--mb-color-border)" }}
+ >
+ <Button variant="subtle" onClick={onCancel}>
+ {t`Cancel`}
+ </Button>
+ <Button variant="filled" onClick={onSave} disabled={!editor.canSave}>
+ {t`Save theme`}
+ </Button>
+ </Flex>
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/EmbeddingThemeEditorApp.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EmbeddingThemeEditorApp.tsx
new file mode 100644
index 00000000000..94f60797a0d
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EmbeddingThemeEditorApp.tsx
@@ -0,0 +1,95 @@
+import { useRef } from "react";
+import type { Route } from "react-router";
+import { push } from "react-router-redux";
+
+import { useDeleteThemeFlow } from "metabase/admin/embedding/hooks";
+import { useEmbeddingThemeEditor } from "metabase/admin/embedding/hooks/use-embedding-theme-editor";
+import { NotFound } from "metabase/common/components/ErrorPages";
+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal/LeaveRouteConfirmModal";
+import { useBeforeUnload } from "metabase/common/hooks/use-before-unload";
+import { useDispatch } from "metabase/redux";
+import { Flex, Loader, Stack } from "metabase/ui";
+
+import { EditorPanel } from "./EditorPanel";
+import { PreviewPanel } from "./PreviewPanel";
+
+interface EmbeddingThemeEditorAppProps {
+ params: { themeId: string };
+ route: Route;
+}
+
+export function EmbeddingThemeEditorApp({
+ params,
+ route,
+}: EmbeddingThemeEditorAppProps) {
+ const themeId =
+ params.themeId === "new" ? "new" : parseInt(params.themeId, 10);
+ const editor = useEmbeddingThemeEditor(themeId);
+ const dispatch = useDispatch();
+ // Suppresses the unsaved-changes prompt when we navigate away intentionally
+ // (save or delete), since those flows leave the editor while `isDirty` is true.
+ const isSavingRef = useRef(false);
+
+ const goToThemeList = () => {
+ dispatch(push("/admin/embedding/themes"));
+ };
+
+ const {
+ requestDelete,
+ modal: deleteModal,
+ isDeleting,
+ } = useDeleteThemeFlow({
+ onDeleted: goToThemeList,
+ });
+
+ // Suppress the unsaved-changes prompt during delete: `isDeleting` is set
+ // (state, so it triggers a re-render) before the mutation awaits, ensuring
+ // the LeaveRouteConfirmModal sees `isEnabled=false` before the redirect.
+ const shouldWarnOnLeave =
+ editor.isDirty && !isSavingRef.current && !isDeleting;
+ useBeforeUnload(shouldWarnOnLeave);
+
+ const handleSave = async () => {
+ isSavingRef.current = true;
+ await editor.handleSave();
+ goToThemeList();
+ };
+
+ if (editor.isLoading) {
+ return (
+ <Stack align="center" justify="center" h="100%">
+ <Loader />
+ </Stack>
+ );
+ }
+
+ // During deletion, the GET refetches and 404s after cache invalidation, but
+ // the redirect to the theme list is on its way — don't flash NotFound.
+ if (!isDeleting && (editor.isNotFound || !editor.currentTheme)) {
+ return <NotFound />;
+ }
+
+ if (!editor.currentTheme) {
+ return (
+ <Stack align="center" justify="center" h="100%">
+ <Loader />
+ </Stack>
+ );
+ }
+
+ return (
+ <Flex h="100%" style={{ overflow: "hidden" }}>
+ <EditorPanel
+ editor={editor}
+ onSave={handleSave}
+ onCancel={goToThemeList}
+ onDelete={
+ typeof themeId === "number" ? () => requestDelete(themeId) : undefined
+ }
+ />
+ <PreviewPanel settings={editor.currentTheme.settings} />
+ <LeaveRouteConfirmModal isEnabled={shouldWarnOnLeave} route={route} />
+ {deleteModal}
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/EnableEmbeddingPrompt.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EnableEmbeddingPrompt.tsx
new file mode 100644
index 00000000000..3c595ce7b70
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/EnableEmbeddingPrompt.tsx
@@ -0,0 +1,44 @@
+import { t } from "ttag";
+
+import { useUpdateSettingsMutation } from "metabase/api";
+import { Button, Center, Stack, Text } from "metabase/ui";
+
+interface EnableEmbeddingPromptProps {
+ isEnabled: boolean;
+ isTermsAccepted: boolean;
+}
+
+export function EnableEmbeddingPrompt({
+ isEnabled,
+ isTermsAccepted,
+}: EnableEmbeddingPromptProps) {
+ const [updateSettings] = useUpdateSettingsMutation();
+
+ const handleEnable = async () => {
+ await updateSettings({
+ "enable-embedding-simple": true,
+ ...(!isTermsAccepted && { "show-simple-embed-terms": false }),
+ });
+ };
+
+ const message = !isEnabled
+ ? t`Enable modular embedding to see a live preview of your theme.`
+ : t`Accept the usage conditions to see a live preview of your theme.`;
+
+ const buttonLabel = !isEnabled
+ ? t`Enable modular embedding`
+ : t`Accept and continue`;
+
+ return (
+ <Center h="100%">
+ <Stack align="center" gap="md" maw={400}>
+ <Text ta="center" c="text-secondary">
+ {message}
+ </Text>
+ <Button variant="filled" onClick={handleEnable}>
+ {buttonLabel}
+ </Button>
+ </Stack>
+ </Center>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.module.css b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.module.css
new file mode 100644
index 00000000000..d2a056723e8
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.module.css
@@ -0,0 +1,10 @@
+.PreviewContainer {
+ box-shadow: 0 6px 24px 0 rgba(0, 0, 0, 0.1);
+ border-radius: var(--mb-radius-md, 8px);
+ overflow: hidden;
+}
+
+.PreviewContainer > * {
+ /* makes the metabase-dashboard element full height */
+ height: 100%;
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.tsx
new file mode 100644
index 00000000000..393dc7d608b
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.tsx
@@ -0,0 +1,62 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import { useSetting } from "metabase/common/hooks";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+import { Box, Center, Flex, Loader, Text } from "metabase/ui";
+
+import { EnableEmbeddingPrompt } from "./EnableEmbeddingPrompt";
+import { PreviewResourcePicker } from "./PreviewResourcePicker";
+import { ResourcePreview } from "./ResourcePreview";
+import type { PreviewResource } from "./types";
+import { useDefaultPreviewResource } from "./use-default-preview-resource";
+
+export function PreviewPanel({ settings }: { settings: MetabaseTheme }) {
+ const isSimpleEmbeddingEnabled = useSetting("enable-embedding-simple");
+ const isTermsAccepted = !useSetting("show-simple-embed-terms");
+
+ const isEmbeddingReady = isSimpleEmbeddingEnabled && isTermsAccepted;
+
+ const [selectedResource, setSelectedResource] =
+ useState<PreviewResource | null>(null);
+ const { resource: defaultResource, isLoading: isDefaultResourceLoading } =
+ useDefaultPreviewResource();
+
+ const resource = selectedResource ?? defaultResource;
+
+ return (
+ <Flex direction="column" flex={1} bg="background-secondary">
+ <Box p="xl" pb="sm">
+ <Flex align="center" justify="space-between" gap="md">
+ <Text fw={700} fz="xl">{t`Theme preview`}</Text>
+ {isEmbeddingReady && resource && (
+ <PreviewResourcePicker
+ resource={resource}
+ onChange={setSelectedResource}
+ />
+ )}
+ </Flex>
+ </Box>
+ <Box flex={1} p="xl" pt="sm" style={{ overflow: "hidden" }}>
+ {!isEmbeddingReady ? (
+ <EnableEmbeddingPrompt
+ isEnabled={isSimpleEmbeddingEnabled}
+ isTermsAccepted={isTermsAccepted}
+ />
+ ) : isDefaultResourceLoading ? (
+ <Center h="100%">
+ <Loader />
+ </Center>
+ ) : resource ? (
+ <ResourcePreview theme={settings} resource={resource} />
+ ) : (
+ <Center h="100%">
+ <Text c="text-secondary">
+ {t`Create a dashboard or question to preview this theme.`}
+ </Text>
+ </Center>
+ )}
+ </Box>
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.unit.spec.tsx
new file mode 100644
index 00000000000..333f9529b15
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewPanel.unit.spec.tsx
@@ -0,0 +1,80 @@
+import {
+ setupRecentViewsEndpoints,
+ setupSearchEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen } from "__support__/ui";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+import { createMockState } from "metabase/redux/store/mocks";
+import { createMockSearchResult } from "metabase-types/api/mocks";
+
+import { PreviewPanel } from "./PreviewPanel";
+import type { PreviewResource } from "./types";
+
+jest.mock("./ResourcePreview", () => ({
+ ResourcePreview: ({ resource }: { resource: PreviewResource }) => (
+ <div
+ data-testid="resource-preview"
+ data-resource-model={resource.model}
+ data-resource-id={resource.id}
+ >
+ {resource.name}
+ </div>
+ ),
+}));
+
+const setup = ({
+ searchItems = [],
+}: {
+ searchItems?: Parameters<typeof setupSearchEndpoints>[0];
+} = {}) => {
+ setupRecentViewsEndpoints([]);
+ setupSearchEndpoints(searchItems);
+
+ const storeInitialState = createMockState({
+ settings: mockSettings({
+ "enable-embedding-simple": true,
+ "show-simple-embed-terms": false,
+ }),
+ });
+
+ return renderWithProviders(<PreviewPanel settings={{} as MetabaseTheme} />, {
+ storeInitialState,
+ });
+};
+
+describe("PreviewPanel", () => {
+ it("falls back to a question when no dashboard exists", async () => {
+ setup({
+ searchItems: [
+ createMockSearchResult({
+ id: 200,
+ model: "card",
+ name: "Only question",
+ }),
+ ],
+ });
+
+ const preview = await screen.findByTestId("resource-preview");
+ expect(preview).toHaveAttribute("data-resource-model", "card");
+ expect(preview).toHaveAttribute("data-resource-id", "200");
+ expect(preview).toHaveTextContent("Only question");
+ expect(
+ screen.getByRole("button", { name: "Change preview resource" }),
+ ).toHaveTextContent("Only question");
+ });
+
+ it("shows the empty-state message when no resource is available", async () => {
+ setup({ searchItems: [] });
+
+ expect(
+ await screen.findByText(
+ "Create a dashboard or question to preview this theme.",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("resource-preview")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Change preview resource" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewResourcePicker.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewResourcePicker.tsx
new file mode 100644
index 00000000000..89a1b7cbe73
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/PreviewResourcePicker.tsx
@@ -0,0 +1,71 @@
+import { useDisclosure } from "@mantine/hooks";
+import { t } from "ttag";
+
+import {
+ EntityPickerModal,
+ type OmniPickerItem,
+} from "metabase/common/components/Pickers";
+import { Button, Icon } from "metabase/ui";
+
+import type { PreviewResource } from "./types";
+
+interface PreviewResourcePickerProps {
+ resource: PreviewResource;
+ onChange: (resource: PreviewResource) => void;
+}
+
+const SELECTABLE_MODELS: OmniPickerItem["model"][] = ["dashboard", "card"];
+
+export function PreviewResourcePicker({
+ resource,
+ onChange,
+}: PreviewResourcePickerProps) {
+ const [isPickerOpen, { open: openPicker, close: closePicker }] =
+ useDisclosure(false);
+
+ const handleChange = (item: OmniPickerItem) => {
+ if (
+ (item.model === "dashboard" || item.model === "card") &&
+ typeof item.id === "number"
+ ) {
+ onChange({
+ model: item.model,
+ id: item.id,
+ name: item.name,
+ });
+ closePicker();
+ }
+ };
+
+ return (
+ <>
+ <Button
+ variant="default"
+ rightSection={<Icon name="chevrondown" size={12} />}
+ onClick={openPicker}
+ aria-label={t`Change preview resource`}
+ >
+ {resource.name}
+ </Button>
+
+ {isPickerOpen && (
+ <EntityPickerModal
+ title={t`Select data to preview`}
+ models={SELECTABLE_MODELS}
+ value={{ id: resource.id, model: resource.model }}
+ onChange={handleChange}
+ onClose={closePicker}
+ isSelectableItem={isSelectableItem}
+ options={{
+ hasConfirmButtons: false,
+ hasPersonalCollections: true,
+ hasRootCollection: true,
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+const isSelectableItem = (item: OmniPickerItem) =>
+ item.model === "dashboard" || item.model === "card";
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx
new file mode 100644
index 00000000000..214a077e5ef
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/ResourcePreview.tsx
@@ -0,0 +1,137 @@
+import {
+ createElement,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { match } from "ts-pattern";
+
+import { useSetting } from "metabase/common/hooks";
+import { METABASE_CONFIG_IS_PROXY_FIELD_NAME } from "metabase/embedding/embedding-iframe-sdk/constants";
+import { setupConfigWatcher } from "metabase/embedding/embedding-iframe-sdk/embed";
+import type { SdkIframeEmbedBaseSettings } from "metabase/embedding/embedding-iframe-sdk/types/embed";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+import { Box, Center, Loader } from "metabase/ui";
+
+import S from "./PreviewPanel.module.css";
+import type { PreviewResource } from "./types";
+
+declare global {
+ interface Window {
+ metabaseConfig?: Partial<SdkIframeEmbedBaseSettings> & {
+ [METABASE_CONFIG_IS_PROXY_FIELD_NAME]?: boolean;
+ };
+ }
+}
+
+export function ResourcePreview({
+ theme,
+ resource,
+}: {
+ theme: MetabaseTheme;
+ resource: PreviewResource;
+}) {
+ const [isLoading, setIsLoading] = useState(true);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const instanceUrl = useSetting("site-url");
+
+ const defineMetabaseConfig = useCallback(
+ (config: SdkIframeEmbedBaseSettings) => {
+ window.metabaseConfig = config;
+
+ if (!window.metabaseConfig[METABASE_CONFIG_IS_PROXY_FIELD_NAME]) {
+ setupConfigWatcher();
+ }
+ },
+ [],
+ );
+
+ const metabaseConfig = useMemo(
+ () => ({
+ instanceUrl,
+ theme,
+ useExistingUserSession: true,
+ }),
+ [instanceUrl, theme],
+ );
+
+ // Initial configuration before first render
+ if (!window.metabaseConfig?.instanceUrl) {
+ defineMetabaseConfig(metabaseConfig);
+ }
+
+ useEffect(() => {
+ defineMetabaseConfig(metabaseConfig);
+ }, [metabaseConfig, defineMetabaseConfig]);
+
+ useEffect(
+ () => () => {
+ if (window.metabaseConfig) {
+ delete window.metabaseConfig;
+ }
+ },
+ [],
+ );
+
+ const { componentName, attributes } = getResourceElement(resource);
+
+ // Track loading state via the "ready" event on the web component
+ useEffect(() => {
+ if (containerRef.current) {
+ const embed = containerRef.current.querySelector(componentName);
+ const handleReady = () => setIsLoading(false);
+
+ if (embed) {
+ setIsLoading(true);
+ embed.addEventListener("ready", handleReady);
+ return () => embed.removeEventListener("ready", handleReady);
+ }
+ }
+ }, [componentName, resource.id]);
+
+ return (
+ <Box
+ className={S.PreviewContainer}
+ ref={containerRef}
+ h="100%"
+ pos="relative"
+ style={{ backgroundColor: theme?.colors?.background }}
+ >
+ {createElement(componentName, attributes)}
+
+ {isLoading && (
+ <Box
+ pos="absolute"
+ inset={0}
+ style={{
+ backgroundColor:
+ theme?.colors?.background ?? "var(--mb-color-background-primary)",
+ }}
+ >
+ <Center h="100%" w="100%">
+ <Loader />
+ </Center>
+ </Box>
+ )}
+ </Box>
+ );
+}
+
+const getResourceElement = (
+ resource: PreviewResource,
+): {
+ componentName: "metabase-dashboard" | "metabase-question";
+ attributes: Record<string, string>;
+} =>
+ match(resource)
+ .with({ model: "dashboard" }, ({ id }) => ({
+ componentName: "metabase-dashboard" as const,
+ attributes: { "dashboard-id": String(id) },
+ }))
+ .with({ model: "card" }, ({ id }) => ({
+ componentName: "metabase-question" as const,
+ attributes: { "question-id": String(id) },
+ }))
+ .exhaustive();
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/constants.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/constants.ts
new file mode 100644
index 00000000000..512aa304e5c
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/constants.ts
@@ -0,0 +1,54 @@
+import { t } from "ttag";
+
+import type { MetabaseColor } from "metabase/embedding-sdk/theme";
+import { ACCENT_COUNT } from "metabase/ui/colors/palette";
+
+export const FONT_FAMILY_OPTIONS: { value: string; label: string }[] = [
+ { value: "Roboto", label: "Roboto" },
+ { value: "Merriweather", label: "Merriweather" },
+ { value: "Open Sans", label: "Open Sans" },
+ { value: "Lato", label: "Lato" },
+ { value: "Noto Sans", label: "Noto Sans" },
+ { value: "Roboto Slab", label: "Roboto Slab" },
+ { value: "Source Sans Pro", label: "Source Sans Pro" },
+ { value: "Raleway", label: "Raleway" },
+ { value: "Slabo 27px", label: "Slabo 27px" },
+ { value: "PT Sans", label: "PT Sans" },
+ { value: "Poppins", label: "Poppins" },
+ { value: "PT Serif", label: "PT Serif" },
+ { value: "Roboto Mono", label: "Roboto Mono" },
+ { value: "Roboto Condensed", label: "Roboto Condensed" },
+ { value: "Playfair Display", label: "Playfair Display" },
+ { value: "Oswald", label: "Oswald" },
+ { value: "Ubuntu", label: "Ubuntu" },
+ { value: "Montserrat", label: "Montserrat" },
+ { value: "Lora", label: "Lora" },
+];
+
+export const PRIMARY_COLORS: {
+ key: Exclude<MetabaseColor, "charts">;
+ label: () => string;
+}[] = [
+ { key: "brand", label: () => t`Brand` },
+ { key: "background", label: () => t`Background` },
+ { key: "text-primary", label: () => t`Primary text` },
+];
+
+export const MORE_COLORS: {
+ key: Exclude<MetabaseColor, "charts">;
+ label: () => string;
+}[] = [
+ { key: "text-secondary", label: () => t`Secondary text` },
+ { key: "text-tertiary", label: () => t`Tertiary text` },
+ { key: "border", label: () => t`Border` },
+ // https://linear.app/metabase/issue/EMB-1627/re-enable-secondary-background-and-use-it-in-sdk-dashboards
+ // TODO Re-enable this once we actually use it in embedded dashboards and questions
+ // { key: "background-secondary", label: () => t`Second. background` },
+ { key: "filter", label: () => t`Filter` },
+ { key: "summarize", label: () => t`Summarize` },
+ { key: "positive", label: () => t`Positive` },
+ { key: "negative", label: () => t`Negative` },
+ { key: "shadow", label: () => t`Shadow` },
+];
+
+export const CHART_COLOR_COUNT = ACCENT_COUNT;
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.ts
new file mode 100644
index 00000000000..25af2c03457
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.ts
@@ -0,0 +1,32 @@
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+
+/**
+ * Serializes the theme settings into a JSON snippet that can be pasted into an
+ * embedding config (e.g. `defineMetabaseConfig({ theme: ... })` or
+ * `<MetabaseProvider config={{ theme: ... }} />`). Empty color values are
+ * stripped so the snippet stays focused on what the admin actually configured.
+ */
+export function getThemeCodeSnippet(settings: MetabaseTheme): string {
+ return JSON.stringify(stripEmptyColors(settings), null, 2);
+}
+
+function stripEmptyColors(settings: MetabaseTheme): MetabaseTheme {
+ if (!settings.colors) {
+ return settings;
+ }
+
+ const cleanedColors = Object.fromEntries(
+ Object.entries(settings.colors).filter(([, value]) => {
+ if (Array.isArray(value)) {
+ return value.length > 0;
+ }
+ return value !== "" && value != null;
+ }),
+ );
+
+ if (Object.keys(cleanedColors).length === 0) {
+ const { colors: _omit, ...rest } = settings;
+ return rest;
+ }
+ return { ...settings, colors: cleanedColors as MetabaseTheme["colors"] };
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.unit.spec.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.unit.spec.ts
new file mode 100644
index 00000000000..f5e567aa49c
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/get-theme-code-snippet.unit.spec.ts
@@ -0,0 +1,57 @@
+import { getThemeCodeSnippet } from "./get-theme-code-snippet";
+
+describe("getThemeCodeSnippet", () => {
+ it("formats settings as pretty-printed JSON", () => {
+ const snippet = getThemeCodeSnippet({
+ colors: { brand: "#509ee3" },
+ fontFamily: "Lato",
+ });
+
+ expect(snippet).toBe(
+ [
+ "{",
+ ` "colors": {`,
+ ` "brand": "#509ee3"`,
+ " },",
+ ` "fontFamily": "Lato"`,
+ "}",
+ ].join("\n"),
+ );
+ });
+
+ it("strips empty color values so the snippet only includes set colors", () => {
+ const snippet = getThemeCodeSnippet({
+ colors: {
+ brand: "#509ee3",
+ background: "",
+ "text-primary": undefined,
+ },
+ });
+
+ const parsed = JSON.parse(snippet);
+ expect(parsed.colors).toEqual({ brand: "#509ee3" });
+ });
+
+ it("keeps the chart colors array when populated", () => {
+ const snippet = getThemeCodeSnippet({
+ colors: { charts: ["#509ee3", "#88bf4d"] },
+ });
+
+ const parsed = JSON.parse(snippet);
+ expect(parsed.colors.charts).toEqual(["#509ee3", "#88bf4d"]);
+ });
+
+ it("omits the colors key entirely when every color is empty", () => {
+ const snippet = getThemeCodeSnippet({
+ colors: { brand: "", background: "" },
+ fontFamily: "Lato",
+ });
+
+ const parsed = JSON.parse(snippet);
+ expect(parsed).toEqual({ fontFamily: "Lato" });
+ });
+
+ it("returns an empty object snippet when no settings are configured", () => {
+ expect(getThemeCodeSnippet({})).toBe("{}");
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/index.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/index.ts
new file mode 100644
index 00000000000..fc5816960c5
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/index.ts
@@ -0,0 +1 @@
+export { EmbeddingThemeEditorApp } from "./EmbeddingThemeEditorApp";
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/types.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/types.ts
new file mode 100644
index 00000000000..6d8f0902f84
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/types.ts
@@ -0,0 +1,3 @@
+export type PreviewResource =
+ | { model: "dashboard"; id: number; name: string }
+ | { model: "card"; id: number; name: string };
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.ts b/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.ts
new file mode 100644
index 00000000000..419de738fd8
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.ts
@@ -0,0 +1,97 @@
+import { useMemo } from "react";
+
+import { useListRecentsQuery, useSearchQuery } from "metabase/api";
+
+import type { PreviewResource } from "./types";
+
+/**
+ * Resolves a default resource to show in the theme preview: the most recently
+ * viewed dashboard, falling back to the most recently viewed question. If the
+ * user has no recent views (e.g. fresh install), falls back to any existing
+ * dashboard, then any existing question.
+ */
+export function useDefaultPreviewResource(): {
+ resource: PreviewResource | null;
+ isLoading: boolean;
+} {
+ const { data: recents = [], isLoading: isRecentsLoading } =
+ useListRecentsQuery({
+ context: ["views"],
+ });
+
+ const recentResource = useMemo(() => pickRecentResource(recents), [recents]);
+
+ const shouldFallback = !isRecentsLoading && recentResource == null;
+
+ const { data: dashboards, isLoading: isDashboardLoading } = useSearchQuery(
+ { models: ["dashboard"], limit: 1 },
+ { skip: !shouldFallback },
+ );
+
+ const dashboard = dashboards?.data?.[0];
+ const hasDashboard = dashboard != null && typeof dashboard.id === "number";
+
+ const { data: questions, isLoading: isQuestionLoading } = useSearchQuery(
+ { models: ["card"], limit: 1 },
+ { skip: !shouldFallback || isDashboardLoading || hasDashboard },
+ );
+
+ const question = questions?.data?.[0];
+
+ return useMemo(() => {
+ if (recentResource) {
+ return { resource: recentResource, isLoading: false };
+ }
+
+ if (hasDashboard && typeof dashboard.id === "number") {
+ return {
+ resource: {
+ model: "dashboard",
+ id: dashboard.id,
+ name: dashboard.name,
+ },
+ isLoading: false,
+ };
+ }
+
+ if (question && typeof question.id === "number") {
+ return {
+ resource: {
+ model: "card",
+ id: question.id,
+ name: question.name,
+ },
+ isLoading: false,
+ };
+ }
+
+ return {
+ resource: null,
+ isLoading: isRecentsLoading || isDashboardLoading || isQuestionLoading,
+ };
+ }, [
+ recentResource,
+ hasDashboard,
+ dashboard,
+ question,
+ isRecentsLoading,
+ isDashboardLoading,
+ isQuestionLoading,
+ ]);
+}
+
+function pickRecentResource(
+ recents: { model: string; id: number; name: string }[],
+): PreviewResource | null {
+ const dashboard = recents.find((item) => item.model === "dashboard");
+ if (dashboard) {
+ return { model: "dashboard", id: dashboard.id, name: dashboard.name };
+ }
+
+ const card = recents.find((item) => item.model === "card");
+ if (card) {
+ return { model: "card", id: card.id, name: card.name };
+ }
+
+ return null;
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.unit.spec.tsx
new file mode 100644
index 00000000000..65a6058f512
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeEditor/use-default-preview-resource.unit.spec.tsx
@@ -0,0 +1,131 @@
+import {
+ setupRecentViewsEndpoints,
+ setupSearchEndpoints,
+} from "__support__/server-mocks";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import {
+ createMockRecentCollectionItem,
+ createMockSearchResult,
+} from "metabase-types/api/mocks";
+
+import { useDefaultPreviewResource } from "./use-default-preview-resource";
+
+const setup = ({
+ recents = [],
+ searchItems = [],
+}: {
+ recents?: Parameters<typeof setupRecentViewsEndpoints>[0];
+ searchItems?: Parameters<typeof setupSearchEndpoints>[0];
+} = {}) => {
+ setupRecentViewsEndpoints(recents);
+ setupSearchEndpoints(searchItems);
+
+ return renderHookWithProviders(() => useDefaultPreviewResource(), {});
+};
+
+describe("useDefaultPreviewResource", () => {
+ it("returns the most recently viewed dashboard when available", async () => {
+ const { result } = setup({
+ recents: [
+ createMockRecentCollectionItem({
+ id: 42,
+ model: "dashboard",
+ name: "Recent dashboard",
+ }),
+ createMockRecentCollectionItem({
+ id: 7,
+ model: "card",
+ name: "Recent question",
+ }),
+ ],
+ });
+
+ await waitFor(() => {
+ expect(result.current.resource).toEqual({
+ model: "dashboard",
+ id: 42,
+ name: "Recent dashboard",
+ });
+ });
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("falls back to the most recently viewed question when no dashboard is in recents", async () => {
+ const { result } = setup({
+ recents: [
+ createMockRecentCollectionItem({
+ id: 9,
+ model: "card",
+ name: "Recent question",
+ }),
+ ],
+ });
+
+ await waitFor(() => {
+ expect(result.current.resource).toEqual({
+ model: "card",
+ id: 9,
+ name: "Recent question",
+ });
+ });
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("falls back to search for a dashboard when recents is empty", async () => {
+ const { result } = setup({
+ recents: [],
+ searchItems: [
+ createMockSearchResult({
+ id: 100,
+ model: "dashboard",
+ name: "Some dashboard",
+ }),
+ createMockSearchResult({
+ id: 101,
+ model: "card",
+ name: "Some question",
+ }),
+ ],
+ });
+
+ await waitFor(() => {
+ expect(result.current.resource).toEqual({
+ model: "dashboard",
+ id: 100,
+ name: "Some dashboard",
+ });
+ });
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("falls back to search for a question when recents is empty and no dashboards exist", async () => {
+ const { result } = setup({
+ recents: [],
+ searchItems: [
+ createMockSearchResult({
+ id: 200,
+ model: "card",
+ name: "Only question",
+ }),
+ ],
+ });
+
+ await waitFor(() => {
+ expect(result.current.resource).toEqual({
+ model: "card",
+ id: 200,
+ name: "Only question",
+ });
+ });
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("returns a null resource when no recents and no searchable content exist", async () => {
+ const { result } = setup({ recents: [], searchItems: [] });
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false);
+ });
+ expect(result.current.resource).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/DeleteThemeModal.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/DeleteThemeModal.tsx
new file mode 100644
index 00000000000..085d35b63f9
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/DeleteThemeModal.tsx
@@ -0,0 +1,33 @@
+import { t } from "ttag";
+
+import { Button, Flex, Modal, Stack, Text } from "metabase/ui";
+
+interface DeleteThemeModalProps {
+ isOpen: boolean;
+ onCancel: () => void;
+ onDelete: () => void;
+}
+
+export function DeleteThemeModal({
+ isOpen,
+ onCancel,
+ onDelete,
+}: DeleteThemeModalProps) {
+ return (
+ <Modal opened={isOpen} onClose={onCancel} title={t`Delete theme`}>
+ <Stack>
+ <Text>{t`Are you sure you want to delete this theme? This action cannot be undone.`}</Text>
+
+ <Flex justify="flex-end" gap="md">
+ <Button variant="subtle" onClick={onCancel}>
+ {t`Cancel`}
+ </Button>
+
+ <Button variant="filled" color="error" onClick={onDelete}>
+ {t`Delete`}
+ </Button>
+ </Flex>
+ </Stack>
+ </Modal>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCard.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCard.tsx
new file mode 100644
index 00000000000..f89c5130f5d
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCard.tsx
@@ -0,0 +1,97 @@
+import { t } from "ttag";
+
+import { ActionIcon, Card, Flex, Icon, Menu, Text } from "metabase/ui";
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import { EmbeddingThemeCardPreview } from "./EmbeddingThemeCardPreview";
+
+export function EmbeddingThemeCard({
+ theme,
+ onEdit,
+ onDuplicate,
+ onDelete,
+}: {
+ theme: EmbeddingTheme;
+ onEdit: (id: number) => void;
+ onDuplicate: (id: number) => void;
+ onDelete: (id: number) => void;
+}) {
+ return (
+ <Card
+ p={0}
+ withBorder
+ onClick={() => onEdit(theme.id)}
+ style={{ cursor: "pointer" }}
+ >
+ <EmbeddingThemeCardPreview theme={theme.settings} />
+
+ <Flex align="center" justify="space-between" px="md" py="sm">
+ <Text fz="lg" truncate="end" title={theme.name}>
+ {theme.name}
+ </Text>
+
+ <EmbeddingThemeActionMenu
+ theme={theme}
+ onEdit={onEdit}
+ onDuplicate={onDuplicate}
+ onDelete={onDelete}
+ />
+ </Flex>
+ </Card>
+ );
+}
+
+const EmbeddingThemeActionMenu = ({
+ theme,
+ onDuplicate,
+ onDelete,
+ onEdit,
+}: {
+ theme: Omit<EmbeddingTheme, "settings">;
+ onEdit: (id: number) => void;
+ onDuplicate: (id: number) => void;
+ onDelete: (id: number) => void;
+}) => {
+ return (
+ <Menu position="bottom-end">
+ {/* stopPropagation prevents triggering the card's onEdit when clicking the menu */}
+ <Menu.Target>
+ <ActionIcon
+ aria-label={t`Duplicate and delete`}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+
+ <Menu.Dropdown>
+ <Menu.Item
+ onClick={(e: React.MouseEvent) => {
+ e.stopPropagation();
+ onEdit(theme.id);
+ }}
+ >
+ {t`Edit`}
+ </Menu.Item>
+ <Menu.Item
+ onClick={(e: React.MouseEvent) => {
+ e.stopPropagation();
+ onDuplicate(theme.id);
+ }}
+ >
+ {t`Duplicate`}
+ </Menu.Item>
+
+ <Menu.Item
+ c="error"
+ onClick={(e: React.MouseEvent) => {
+ e.stopPropagation();
+ onDelete(theme.id);
+ }}
+ >
+ {t`Delete`}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ );
+};
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.tsx
new file mode 100644
index 00000000000..78a7375f663
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.tsx
@@ -0,0 +1,232 @@
+import { useCallback, useMemo } from "react";
+
+import {
+ DEFAULT_SDK_FONT_SIZE,
+ type MetabaseColor,
+ type MetabaseTheme,
+} from "metabase/embedding-sdk/theme";
+import { getSizeInPx } from "metabase/visualizations/shared/utils/size-in-px";
+
+import { useDefaultEmbeddingThemeSettings } from "../../hooks";
+
+export const EmbeddingThemeCardPreview = ({
+ theme,
+}: {
+ theme: MetabaseTheme;
+}) => {
+ const { colors } = theme ?? {};
+ const defaultThemeSettings = useDefaultEmbeddingThemeSettings();
+
+ const colorOf = (key: Exclude<MetabaseColor, "charts">) =>
+ colors?.[key] ?? defaultThemeSettings.colors?.[key];
+
+ // Get preview font sizes.
+ const getPreviewValue = useCallback(
+ (pxValue: number) => {
+ const emValue = pxValue / DEFAULT_SDK_FONT_SIZE;
+ const baseFontSize = getSizeInPx(theme.fontSize) ?? DEFAULT_SDK_FONT_SIZE;
+
+ return getSizeInPx(`${emValue}em`, baseFontSize);
+ },
+ [theme.fontSize],
+ );
+
+ const [h1FontSize, h2FontSize, smFontSize] = useMemo(
+ () => [getPreviewValue(24), getPreviewValue(16), getPreviewValue(12)],
+ [getPreviewValue],
+ );
+
+ const chartColorOf = (index: number): string => {
+ const color =
+ colors?.charts?.[index] ?? defaultThemeSettings.colors?.charts?.[index];
+
+ // The SDK can take an object of {base, tint?, shade?} for chart colors.
+ if (typeof color === "object" && color.base) {
+ return color.base;
+ }
+
+ if (typeof color === "string") {
+ return color;
+ }
+
+ return "";
+ };
+
+ const chart0 = chartColorOf(0);
+ const chart1 = chartColorOf(1);
+ const chart2 = chartColorOf(2);
+
+ return (
+ <svg
+ viewBox="0 0 250 250"
+ fill="none"
+ style={{
+ borderBottom: "1px solid var(--mb-color-border)",
+ fontFamily: theme.fontFamily ?? "inherit",
+ }}
+ >
+ <g>
+ <defs>
+ <filter
+ id="theme-preview-drop-shadow"
+ x="-20%"
+ y="-20%"
+ width="140%"
+ height="140%"
+ >
+ <feDropShadow dx="2" dy="4" stdDeviation="4" floodOpacity="0.2" />
+ </filter>
+ </defs>
+ <path d="M0 0H251V251H0V0Z" fill={colorOf("background")} />
+
+ <text
+ x="28"
+ y="48"
+ fill={colorOf("text-primary")}
+ fontSize={h1FontSize}
+ fontWeight="600"
+ >
+ {"Abc"}
+ </text>
+
+ <g>
+ <rect
+ x="85"
+ y="30"
+ width="56"
+ height="20"
+ rx="4"
+ fill={colorOf("brand")}
+ />
+ <text
+ x="113"
+ y="44"
+ fill="#FFFFFF"
+ fontSize="11"
+ fontWeight="600"
+ textAnchor="middle"
+ >
+ {"Button"}
+ </text>
+ </g>
+
+ <rect
+ x="28"
+ y="69"
+ width="435"
+ height="269"
+ rx="6"
+ fill={colorOf("background")}
+ filter="url(#theme-preview-drop-shadow)"
+ />
+
+ <rect
+ x="28.5"
+ y="69.5"
+ width="434"
+ height="268"
+ rx="5.5"
+ stroke="#071722"
+ strokeOpacity="0.14"
+ />
+
+ <line x1="97" y1="142.5" x2="437" y2="142.5" stroke="#EEECEC" />
+ <line x1="97" y1="188.5" x2="437" y2="188.5" stroke="#EEECEC" />
+ <line x1="97" y1="235.5" x2="437" y2="235.5" stroke="#EEECEC" />
+
+ <text
+ x="60"
+ y="147"
+ fill={colorOf("text-secondary")}
+ fontSize={smFontSize}
+ >
+ 300
+ </text>
+ <text
+ x="60"
+ y="193"
+ fill={colorOf("text-secondary")}
+ fontSize={smFontSize}
+ >
+ 200
+ </text>
+ <text
+ x="60"
+ y="239"
+ fill={colorOf("text-secondary")}
+ fontSize={smFontSize}
+ >
+ 100
+ </text>
+
+ <text
+ x="60"
+ y="107"
+ fill={colorOf("text-primary")}
+ fontSize={h2FontSize}
+ fontWeight="700"
+ >
+ {"Theme preview"}
+ </text>
+
+ <rect x="97" y="236.539" width="18.77" height="13.4699" fill={chart0} />
+ <rect x="97" y="206.758" width="18.77" height="29.7755" fill={chart1} />
+ <rect x="97" y="194" width="18.77" height="12.7609" fill={chart2} />
+ <rect
+ x="132"
+ y="232.445"
+ width="18.77"
+ height="17.5579"
+ fill={chart0}
+ />
+ <rect
+ x="132"
+ y="193.633"
+ width="18.77"
+ height="38.8122"
+ fill={chart1}
+ />
+ <rect x="132" y="177" width="18.77" height="16.6338" fill={chart2} />
+ <rect
+ x="167"
+ y="229.078"
+ width="18.77"
+ height="20.9251"
+ fill={chart0}
+ />
+ <rect
+ x="167"
+ y="182.824"
+ width="18.77"
+ height="46.2556"
+ fill={chart1}
+ />
+ <rect x="167" y="163" width="18.77" height="19.8238" fill={chart2} />
+ <rect
+ x="202"
+ y="226.191"
+ width="18.77"
+ height="23.8107"
+ fill={chart0}
+ />
+ <rect
+ x="202"
+ y="173.559"
+ width="18.77"
+ height="52.6342"
+ fill={chart1}
+ />
+ <rect x="202" y="151" width="18.77" height="22.5575" fill={chart2} />
+ <rect
+ x="237"
+ y="221.859"
+ width="18.77"
+ height="28.1393"
+ fill={chart0}
+ />
+ <rect x="237" y="159.66" width="18.77" height="62.2027" fill={chart1} />
+ <rect x="237" y="133" width="18.77" height="26.6583" fill={chart2} />
+ </g>
+ </svg>
+ );
+};
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.unit.spec.tsx
new file mode 100644
index 00000000000..b763d197d94
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeCardPreview.unit.spec.tsx
@@ -0,0 +1,63 @@
+import { renderWithProviders, screen } from "__support__/ui";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+
+import { EmbeddingThemeCardPreview } from "./EmbeddingThemeCardPreview";
+
+const TEST_THEME: MetabaseTheme = {
+ fontFamily: "Roboto",
+ fontSize: "14px",
+ colors: {
+ background: "#ffffff",
+ "text-primary": "#223344",
+ "text-secondary": "#667788",
+ charts: ["#ff0000", "#00ff00", "#0000ff"],
+ },
+};
+
+function setup(theme: MetabaseTheme = TEST_THEME) {
+ return renderWithProviders(<EmbeddingThemeCardPreview theme={theme} />);
+}
+
+describe("EmbeddingThemeCardPreview", () => {
+ it("applies the font family from the theme", () => {
+ setup();
+
+ const svg = document.querySelector("svg");
+ expect(svg).toHaveStyle({ fontFamily: "Roboto" });
+ });
+
+ it("uses the background color for the card background", () => {
+ setup();
+
+ const backgroundPath = document.querySelector("path");
+ expect(backgroundPath).toHaveAttribute("fill", "#ffffff");
+ });
+
+ it("uses the text-primary color for the heading text", () => {
+ setup();
+
+ const headingText = screen.getByText("Abc");
+ expect(headingText).toHaveAttribute("fill", "#223344");
+ });
+
+ it("uses the text-primary color for the chart title text", () => {
+ setup();
+
+ const chartTitle = screen.getByText("Theme preview");
+ expect(chartTitle).toHaveAttribute("fill", "#223344");
+ });
+
+ it("uses the text-secondary color for axis labels", () => {
+ setup();
+
+ const axisLabel = screen.getByText("300");
+ expect(axisLabel).toHaveAttribute("fill", "#667788");
+ });
+
+ it("falls back to 'inherit' when no font family is specified", () => {
+ setup({ colors: TEST_THEME.colors });
+
+ const svg = document.querySelector("svg");
+ expect(svg).toHaveStyle({ fontFamily: "inherit" });
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.tsx
new file mode 100644
index 00000000000..4032eb6e6d4
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.tsx
@@ -0,0 +1,81 @@
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { useDeleteThemeFlow } from "metabase/admin/embedding/hooks";
+import { UpsellEmbeddingTheme } from "metabase/admin/upsells";
+import {
+ useCopyEmbeddingThemeMutation,
+ useListEmbeddingThemesQuery,
+} from "metabase/api/embedding-theme";
+import { useHasTokenFeature, useToast } from "metabase/common/hooks";
+import { useDispatch } from "metabase/redux";
+import { Loader, SimpleGrid, Stack, Text, Title } from "metabase/ui";
+
+import { EmbeddingThemeCard } from "./EmbeddingThemeCard";
+import { NewThemeCard } from "./NewThemeCard";
+
+export function EmbeddingThemeListingApp() {
+ const hasSimpleEmbedding = useHasTokenFeature("embedding_simple");
+
+ if (!hasSimpleEmbedding) {
+ return <UpsellEmbeddingTheme source="embedding-themes" />;
+ }
+
+ return <EmbeddingThemeListingAppInner />;
+}
+
+function EmbeddingThemeListingAppInner() {
+ const dispatch = useDispatch();
+ const { data: themes, isLoading } = useListEmbeddingThemesQuery();
+ const [duplicateTheme] = useCopyEmbeddingThemeMutation();
+ const [sendToast] = useToast();
+ const { requestDelete, modal: deleteModal } = useDeleteThemeFlow();
+
+ const handleCreateTheme = () => {
+ dispatch(push(`/admin/embedding/themes/new`));
+ };
+
+ const handleDuplicateTheme = async (themeId: number) => {
+ try {
+ await duplicateTheme(themeId);
+ sendToast({ message: t`Theme duplicated successfully`, icon: "check" });
+ } catch (error) {
+ console.error("Failed to duplicate theme:", error);
+ sendToast({ message: t`Failed to duplicate theme`, icon: "warning" });
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <Stack align="center" justify="center" h={400}>
+ <Loader />
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack mx="auto" gap="xl" maw={1200}>
+ <Stack gap="xs">
+ <Title order={1}>{t`Themes`}</Title>
+ <Text c="text-secondary">
+ {t`Configure themes for Embedded Analytics JS and SDK for React`}
+ </Text>
+ </Stack>
+
+ <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="md">
+ {themes?.map((theme) => (
+ <EmbeddingThemeCard
+ key={theme.id}
+ theme={theme}
+ onEdit={() => dispatch(push(`/admin/embedding/themes/${theme.id}`))}
+ onDuplicate={() => handleDuplicateTheme(theme.id)}
+ onDelete={() => requestDelete(theme.id)}
+ />
+ ))}
+ <NewThemeCard onClick={handleCreateTheme} />
+ </SimpleGrid>
+
+ {deleteModal}
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.unit.spec.tsx
new file mode 100644
index 00000000000..c85c2be3938
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/EmbeddingThemeListingApp.unit.spec.tsx
@@ -0,0 +1,69 @@
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockSettingsState } from "metabase/redux/store/mocks";
+import {
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { EmbeddingThemeListingApp } from "./EmbeddingThemeListingApp";
+
+const setup = ({
+ hasSimpleEmbedding = false,
+}: {
+ hasSimpleEmbedding?: boolean;
+} = {}) => {
+ fetchMock.get("path:/api/embed-theme", []);
+
+ const settings = createMockSettings({
+ "token-features": createMockTokenFeatures({
+ embedding_simple: hasSimpleEmbedding,
+ }),
+ });
+
+ renderWithProviders(<EmbeddingThemeListingApp />, {
+ storeInitialState: {
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: createMockSettingsState(settings),
+ },
+ });
+};
+
+describe("EmbeddingThemeListingApp", () => {
+ it("renders the themes upsell for OSS/starter users", async () => {
+ setup({ hasSimpleEmbedding: false });
+
+ expect(await screen.findByText("Create custom themes")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("heading", { name: "Themes" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /New theme/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders the themes listing for Pro users", async () => {
+ setup({ hasSimpleEmbedding: true });
+
+ expect(
+ await screen.findByRole("heading", { name: "Themes" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /New theme/ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Create custom themes")).not.toBeInTheDocument();
+ });
+
+ it("does not request themes from the API when showing the upsell", async () => {
+ setup({ hasSimpleEmbedding: false });
+
+ await screen.findByText("Create custom themes");
+
+ // Give RTK Query a chance to fire the request if it were going to.
+ expect(fetchMock.callHistory.calls("path:/api/embed-theme")).toHaveLength(
+ 0,
+ );
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.module.css b/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.module.css
new file mode 100644
index 00000000000..b0260c2e90f
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.module.css
@@ -0,0 +1,19 @@
+.card {
+ position: relative;
+ cursor: pointer;
+ font: inherit;
+ text-align: inherit;
+ transition:
+ background-color 120ms ease,
+ border-color 120ms ease;
+}
+
+.card:hover {
+ border-color: var(--mb-color-brand);
+ background-color: var(--mb-color-background-hover);
+}
+
+.overlay {
+ position: absolute;
+ inset: 0;
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.tsx b/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.tsx
new file mode 100644
index 00000000000..15ab2ff7efc
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/NewThemeCard.tsx
@@ -0,0 +1,28 @@
+import { t } from "ttag";
+
+import { Card, Icon, Stack, Text } from "metabase/ui";
+
+import S from "./NewThemeCard.module.css";
+
+interface NewThemeCardProps {
+ onClick: () => void;
+}
+
+export function NewThemeCard({ onClick }: NewThemeCardProps) {
+ return (
+ <Card
+ withBorder
+ component="button"
+ type="button"
+ p={0}
+ onClick={onClick}
+ className={S.card}
+ h={301}
+ >
+ <Stack className={S.overlay} align="center" justify="center" gap="xs">
+ <Icon name="add" c="brand" size={24} />
+ <Text c="brand" fw={500}>{t`New theme`}</Text>
+ </Stack>
+ </Card>
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/components/ThemeListing/index.ts b/frontend/src/metabase/admin/embedding/components/ThemeListing/index.ts
new file mode 100644
index 00000000000..81a4a7fe70f
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/components/ThemeListing/index.ts
@@ -0,0 +1 @@
+export { EmbeddingThemeListingApp } from "./EmbeddingThemeListingApp";
diff --git a/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.tsx b/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.tsx
index 1792d0a2cfc..829f0540e68 100644
--- a/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.tsx
+++ b/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.tsx
@@ -3,12 +3,19 @@ import type { Location } from "history";
import { AdminSettingsLayout } from "metabase/common/components/AdminLayout/AdminSettingsLayout";
import { EmbeddingNav } from "../components/EmbeddingNav";
+import { useEnsureDefaultEmbeddingThemes } from "../hooks";
const SIDEBAR_HIDDEN_PATHS = new Set([
"/admin/embedding/setup-guide/permissions",
"/admin/embedding/setup-guide/sso",
]);
+// routes in this array won't render the embedding sidebar
+const SIDEBAR_HIDDEN_PATH_PREFIXES = ["/admin/embedding/themes/"];
+
+// routes in this array will take the full width _of the main content area_
+const FULL_CONTENT_WIDTH_PATH_PREFIXES = ["/admin/embedding/themes/"];
+
export const AdminEmbeddingApp = ({
location,
children,
@@ -16,11 +23,22 @@ export const AdminEmbeddingApp = ({
location: Location;
children: React.ReactNode;
}) => {
- const shouldHideSidebar = SIDEBAR_HIDDEN_PATHS.has(location.pathname);
+ useEnsureDefaultEmbeddingThemes();
+
+ const shouldHideSidebar =
+ SIDEBAR_HIDDEN_PATHS.has(location.pathname) ||
+ SIDEBAR_HIDDEN_PATH_PREFIXES.some((prefix) =>
+ location.pathname.startsWith(prefix),
+ );
+
+ const isFullWidth = FULL_CONTENT_WIDTH_PATH_PREFIXES.some((prefix) =>
+ location.pathname.startsWith(prefix),
+ );
return (
<AdminSettingsLayout
sidebar={shouldHideSidebar ? undefined : <EmbeddingNav />}
+ fullWidth={isFullWidth}
>
{children}
</AdminSettingsLayout>
diff --git a/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.unit.spec.tsx b/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.unit.spec.tsx
index 35c81df28af..b340a3e6c42 100644
--- a/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/embedding/containers/AdminEmbeddingApp.unit.spec.tsx
@@ -37,4 +37,25 @@ describe("AdminEmbeddingApp", () => {
).not.toBeInTheDocument();
expect(screen.getByTestId("admin-layout-content")).toBeInTheDocument();
});
+
+ it("hides the sidebar for theme editor paths", () => {
+ renderWithProviders(<Route path="*" component={TestAdminEmbeddingApp} />, {
+ initialRoute: "/admin/embedding/themes/42",
+ withRouter: true,
+ });
+
+ expect(
+ screen.queryByTestId("admin-layout-sidebar"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTestId("admin-layout-content")).toBeInTheDocument();
+ });
+
+ it("shows the sidebar on the themes listing page", () => {
+ renderWithProviders(<Route path="*" component={TestAdminEmbeddingApp} />, {
+ initialRoute: "/admin/embedding/themes",
+ withRouter: true,
+ });
+
+ expect(screen.getByTestId("admin-layout-sidebar")).toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/admin/embedding/hooks/index.ts b/frontend/src/metabase/admin/embedding/hooks/index.ts
new file mode 100644
index 00000000000..770a6fb862f
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/index.ts
@@ -0,0 +1,5 @@
+export { useDefaultEmbeddingThemeSettings } from "./use-default-embedding-theme-settings";
+export { useDeleteThemeFlow } from "./use-delete-theme-flow";
+export { useDefaultEmbeddingThemes } from "./use-default-embedding-themes";
+export { useEmbeddingThemeEditor } from "./use-embedding-theme-editor";
+export { useEnsureDefaultEmbeddingThemes } from "./use-ensure-default-embedding-themes";
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.ts b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.ts
new file mode 100644
index 00000000000..b7ea96b1d81
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.ts
@@ -0,0 +1,24 @@
+import { useMemo } from "react";
+
+import { useSetting } from "metabase/common/hooks";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+
+import { deriveSdkThemeSettings } from "../utils/derive-sdk-theme-settings";
+
+/**
+ * Returns a default embedding theme (Light variant) with colors mapped from the
+ * instance's appearance settings (white-labeled colors).
+ *
+ * Used by the theme editor to reset colors back to defaults and to produce the
+ * default theme object for a newly-created theme.
+ *
+ * TODO(EMB-948): derive this from the theme editor's color configuration instead!
+ */
+export function useDefaultEmbeddingThemeSettings(): MetabaseTheme {
+ const whitelabelColors = useSetting("application-colors");
+
+ return useMemo(
+ () => deriveSdkThemeSettings("light", whitelabelColors ?? {}),
+ [whitelabelColors],
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.unit.spec.tsx b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.unit.spec.tsx
new file mode 100644
index 00000000000..b467a86a2ac
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-theme-settings.unit.spec.tsx
@@ -0,0 +1,52 @@
+import { renderHookWithProviders } from "__support__/ui";
+import type { State } from "metabase/redux/store";
+import { createMockState } from "metabase/redux/store/mocks";
+import { getColors } from "metabase/ui/colors/colors";
+import type { ColorSettings } from "metabase-types/api/settings";
+
+import { useDefaultEmbeddingThemeSettings } from "./use-default-embedding-theme-settings";
+
+const setup = (applicationColors?: ColorSettings) => {
+ const initialState = createMockState({
+ settings: { values: { "application-colors": applicationColors } },
+ } as Partial<State>);
+
+ return renderHookWithProviders(() => useDefaultEmbeddingThemeSettings(), {
+ storeInitialState: initialState,
+ });
+};
+
+describe("useDefaultEmbeddingThemeSettings", () => {
+ it("default colors should match lib/colors/colors.ts", () => {
+ const { result } = setup();
+ const theme = result.current;
+ const expectedColors = getColors();
+
+ expect(theme?.colors?.brand).toBe(expectedColors.brand);
+ expect(theme?.colors?.["text-secondary"]).toBe(
+ expectedColors["text-secondary"],
+ );
+
+ // The SDK maps background-secondary as [background-secondary, background-tertiary]
+ // It should use the first defined value which is "background-secondary"
+ expect(theme?.colors?.["background-secondary"]).toBe(
+ expectedColors["background-secondary"],
+ );
+ });
+
+ it("should use application colors when provided", () => {
+ const { result } = setup({ brand: "#FF5733", filter: "#2D2D30" });
+ const theme = result.current;
+
+ expect(theme?.colors?.brand).toBe("#FF5733");
+ expect(theme?.colors?.filter).toBe("#2D2D30");
+ });
+
+ it("should use white-labeled chart colors when provided", () => {
+ const { result } = setup({ accent0: "#FF0000", accent7: "#0000FF" });
+ const theme = result.current;
+
+ expect(theme?.colors?.charts?.[0]).toBe("#FF0000");
+ expect(theme?.colors?.charts?.[7]).toBe("#0000FF");
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-themes.ts b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-themes.ts
new file mode 100644
index 00000000000..c01c948bd5c
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-default-embedding-themes.ts
@@ -0,0 +1,30 @@
+import { useMemo } from "react";
+import { t } from "ttag";
+
+import { useSetting } from "metabase/common/hooks";
+import type { CreateEmbeddingThemeRequest } from "metabase-types/api";
+
+import { deriveSdkThemeSettings } from "../utils/derive-sdk-theme-settings";
+
+/**
+ * Returns the default `Light` and `Dark` embedding theme payloads, ready to be sent to the
+ * `POST /api/embed-theme/seed-defaults` endpoint. Colors are derived from `METABASE_LIGHT_THEME`
+ * / `METABASE_DARK_THEME` via `deriveFullMetabaseTheme`, with whitelabel overrides applied on top.
+ */
+export function useDefaultEmbeddingThemes(): CreateEmbeddingThemeRequest[] {
+ const whitelabelColors = useSetting("application-colors");
+
+ return useMemo(
+ () => [
+ {
+ name: t`Light`,
+ settings: deriveSdkThemeSettings("light", whitelabelColors ?? {}),
+ },
+ {
+ name: t`Dark`,
+ settings: deriveSdkThemeSettings("dark", whitelabelColors ?? {}),
+ },
+ ],
+ [whitelabelColors],
+ );
+}
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-delete-theme-flow.tsx b/frontend/src/metabase/admin/embedding/hooks/use-delete-theme-flow.tsx
new file mode 100644
index 00000000000..5c62e2b65b6
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-delete-theme-flow.tsx
@@ -0,0 +1,52 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import { useDeleteEmbeddingThemeMutation } from "metabase/api/embedding-theme";
+import { useToast } from "metabase/common/hooks";
+
+import { DeleteThemeModal } from "../components/ThemeListing/DeleteThemeModal";
+
+interface UseDeleteThemeFlowOptions {
+ onDeleted?: () => void;
+}
+
+export function useDeleteThemeFlow({
+ onDeleted,
+}: UseDeleteThemeFlowOptions = {}) {
+ const [deleteTheme] = useDeleteEmbeddingThemeMutation();
+ const [sendToast] = useToast();
+ const [themeToDelete, setThemeToDelete] = useState<number | null>(null);
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ const requestDelete = (themeId: number) => setThemeToDelete(themeId);
+ const cancelDelete = () => setThemeToDelete(null);
+
+ const confirmDelete = async () => {
+ if (themeToDelete === null) {
+ return;
+ }
+ // Prevent the editor from rendering NotFound during the window between
+ // cache invalidation (when the GET refetches and 404s) and the redirect.
+ setIsDeleting(true);
+ try {
+ await deleteTheme(themeToDelete).unwrap();
+ sendToast({ message: t`Theme deleted successfully`, icon: "check" });
+ setThemeToDelete(null);
+ onDeleted?.();
+ } catch (error) {
+ console.error("Failed to delete theme:", error);
+ sendToast({ message: t`Failed to delete theme`, icon: "warning" });
+ setIsDeleting(false);
+ }
+ };
+
+ const modal = (
+ <DeleteThemeModal
+ isOpen={themeToDelete !== null}
+ onCancel={cancelDelete}
+ onDelete={confirmDelete}
+ />
+ );
+
+ return { requestDelete, modal, isDeleting };
+}
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts
new file mode 100644
index 00000000000..0b99fa8b65f
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.ts
@@ -0,0 +1,277 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+import { isEqual } from "underscore";
+
+import { useDefaultEmbeddingThemeSettings } from "metabase/admin/embedding/hooks/use-default-embedding-theme-settings";
+import { skipToken } from "metabase/api";
+import {
+ useCreateEmbeddingThemeMutation,
+ useGetEmbeddingThemeQuery,
+ useUpdateEmbeddingThemeMutation,
+} from "metabase/api/embedding-theme";
+import { useToast } from "metabase/common/hooks";
+import type {
+ MetabaseColor,
+ MetabaseTheme,
+} from "metabase/embedding-sdk/theme";
+import type { EmbeddingTheme } from "metabase-types/api";
+
+interface ThemeEditorState {
+ name: string;
+ settings: MetabaseTheme;
+}
+
+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",
+];
+
+export function useEmbeddingThemeEditor(themeId: ThemeEditorId) {
+ const isDraft = themeId === "new";
+ const {
+ data: serverTheme,
+ isLoading: isLoadingServer,
+ isError,
+ } = useGetEmbeddingThemeQuery(isDraft ? skipToken : themeId);
+ const [createTheme] = useCreateEmbeddingThemeMutation();
+ const [updateTheme] = useUpdateEmbeddingThemeMutation();
+ const [sendToast] = useToast();
+ const defaultThemeSettings = useDefaultEmbeddingThemeSettings();
+
+ // Seed once on mount when in draft mode so the baseline is stable across renders.
+ const [draftInitial] = useState<ThemeEditorState | null>(() =>
+ isDraft
+ ? { name: t`Untitled theme`, settings: defaultThemeSettings }
+ : null,
+ );
+
+ const [currentTheme, setCurrentTheme] = useState<ThemeEditorState | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (currentTheme) {
+ return;
+ }
+ if (isDraft && draftInitial) {
+ setCurrentTheme(draftInitial);
+ } else if (serverTheme) {
+ setCurrentTheme({
+ name: serverTheme.name,
+ settings: serverTheme.settings,
+ });
+ }
+ }, [isDraft, draftInitial, serverTheme, currentTheme]);
+
+ const baselineState = useMemo(() => {
+ if (isDraft) {
+ return draftInitial;
+ }
+ return serverTheme
+ ? { name: serverTheme.name, settings: serverTheme.settings }
+ : null;
+ }, [isDraft, draftInitial, serverTheme]);
+
+ const isDirty = useMemo(
+ () => !isEqual(baselineState, currentTheme),
+ [baselineState, currentTheme],
+ );
+ const canSave = isDraft || isDirty;
+
+ const updateSettings = useCallback(
+ (updater: (settings: MetabaseTheme) => Partial<MetabaseTheme>) => {
+ setCurrentTheme((prev) =>
+ prev
+ ? {
+ ...prev,
+ settings: { ...prev.settings, ...updater(prev.settings) },
+ }
+ : prev,
+ );
+ },
+ [],
+ );
+
+ const setName = useCallback((name: string) => {
+ setCurrentTheme((prev) => (prev ? { ...prev, name } : prev));
+ }, []);
+
+ 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) {
+ return prev;
+ }
+ const { fontFamily: _omit, ...rest } = prev.settings;
+ return {
+ ...prev,
+ settings: family ? { ...rest, fontFamily: family } : rest,
+ };
+ });
+ }, []);
+
+ const setFontSize = useCallback((size: string) => {
+ setCurrentTheme((prev) => {
+ if (!prev) {
+ return prev;
+ }
+ const { fontSize: _omit, ...rest } = prev.settings;
+ return {
+ ...prev,
+ settings: size ? { ...rest, fontSize: size } : rest,
+ };
+ });
+ }, []);
+
+ const hasAdditionalColorChanges = 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 ?? []);
+ }, [currentTheme, defaultThemeSettings]);
+
+ const hasMainColorChanges = 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;
+ }
+ }
+
+ 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 };
+ });
+ }, [updateSettings, defaultThemeSettings]);
+
+ 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 };
+ });
+ }, [updateSettings, defaultThemeSettings]);
+
+ const handleSave = useCallback(async (): Promise<EmbeddingTheme | null> => {
+ if (!currentTheme) {
+ return null;
+ }
+ try {
+ if (isDraft) {
+ const created = await createTheme({
+ name: currentTheme.name || t`Untitled theme`,
+ settings: currentTheme.settings,
+ }).unwrap();
+ sendToast({ message: t`Theme saved`, icon: "check" });
+ return created;
+ }
+ const updated = await updateTheme({
+ id: themeId as number,
+ name: currentTheme.name,
+ settings: currentTheme.settings,
+ }).unwrap();
+ sendToast({ message: t`Theme saved`, icon: "check" });
+ return updated;
+ } catch (error) {
+ console.error("Failed to save theme:", error);
+ sendToast({ message: t`Failed to save theme`, icon: "warning" });
+ return null;
+ }
+ }, [currentTheme, isDraft, themeId, createTheme, updateTheme, sendToast]);
+
+ const handleDiscard = useCallback(() => {
+ setCurrentTheme(baselineState);
+ }, [baselineState]);
+
+ return {
+ isLoading: isDraft ? false : isLoadingServer,
+ isNotFound: isError,
+ isDraft,
+ currentTheme,
+ isDirty,
+ canSave,
+ setName,
+ setColor,
+ setChartColor,
+ hasMainColorChanges,
+ resetMainColors,
+ hasAdditionalColorChanges,
+ resetAdditionalColors,
+ setFontFamily,
+ setFontSize,
+ handleSave,
+ handleDiscard,
+ };
+}
+
+export type EmbeddingThemeEditorResult = ReturnType<
+ typeof useEmbeddingThemeEditor
+>;
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.tsx
new file mode 100644
index 00000000000..949fdfdc56b
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-embedding-theme-editor.unit.spec.tsx
@@ -0,0 +1,377 @@
+import fetchMock from "fetch-mock";
+
+import { act, renderHookWithProviders, waitFor } from "__support__/ui";
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import {
+ type ThemeEditorId,
+ useEmbeddingThemeEditor,
+} from "./use-embedding-theme-editor";
+
+const TEST_THEME: EmbeddingTheme = {
+ id: 1,
+ name: "My theme",
+ settings: {
+ colors: { brand: "#509EE3", background: "#ffffff" },
+ fontFamily: "Roboto",
+ fontSize: "14px",
+ },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+};
+
+function setup(themeId: ThemeEditorId = 1) {
+ if (typeof themeId === "number") {
+ fetchMock.get(`path:/api/embed-theme/${themeId}`, TEST_THEME);
+ fetchMock.put(`path:/api/embed-theme/${themeId}`, {
+ ...TEST_THEME,
+ name: "Updated",
+ });
+ }
+
+ return renderHookWithProviders(() => useEmbeddingThemeEditor(themeId), {
+ withUndos: true,
+ });
+}
+
+describe("useEmbeddingThemeEditor", () => {
+ afterEach(() => {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ });
+
+ it("loads the theme and initializes state", async () => {
+ const { result } = setup();
+
+ expect(result.current.isLoading).toBe(true);
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ expect(result.current.currentTheme?.name).toBe("My theme");
+ expect(result.current.currentTheme?.settings.colors?.brand).toBe("#509EE3");
+ expect(result.current.isDirty).toBe(false);
+ });
+
+ it("tracks dirty state when name changes", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ act(() => {
+ result.current.setName("New name");
+ });
+
+ expect(result.current.currentTheme?.name).toBe("New name");
+ expect(result.current.isDirty).toBe(true);
+ });
+
+ it("tracks dirty state when a color changes", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ act(() => {
+ result.current.setColor("brand", "#FF0000");
+ });
+
+ expect(result.current.currentTheme?.settings.colors?.brand).toBe("#ff0000");
+ expect(result.current.isDirty).toBe(true);
+ });
+
+ it("discards changes and reverts to pristine state", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ act(() => {
+ result.current.setName("Changed name");
+ });
+
+ expect(result.current.isDirty).toBe(true);
+
+ act(() => {
+ result.current.handleDiscard();
+ });
+
+ expect(result.current.currentTheme?.name).toBe("My theme");
+ 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();
+
+ 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();
+ });
+
+ expect(result.current.hasAdditionalColorChanges).toBe(false);
+ });
+
+ it("hasAdditionalColorChanges is true when an additional color differs", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ act(() => {
+ result.current.setColor("border", "#FF00FF");
+ });
+
+ expect(result.current.hasAdditionalColorChanges).toBe(true);
+ });
+
+ it("hasAdditionalColorChanges is true when chart colors differ", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ act(() => {
+ result.current.setChartColor(0, "#FF00FF");
+ });
+
+ expect(result.current.hasAdditionalColorChanges).toBe(true);
+ });
+
+ it("hasAdditionalColorChanges is false for main color changes only", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ // Reset additional colors to defaults first
+ act(() => {
+ result.current.resetAdditionalColors();
+ });
+
+ // Change only a main color
+ act(() => {
+ result.current.setColor("brand", "#123456");
+ });
+
+ expect(result.current.hasAdditionalColorChanges).toBe(false);
+ });
+
+ it("resets additional and chart colors to defaults, preserving main colors", async () => {
+ const { result } = setupWithCustomColors();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.hasAdditionalColorChanges).toBe(true);
+
+ act(() => {
+ result.current.resetAdditionalColors();
+ });
+
+ const colors = result.current.currentTheme?.settings.colors;
+
+ // 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);
+ });
+ });
+
+ describe("clearing font fields", () => {
+ it("removes fontFamily from settings when cleared", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.currentTheme?.settings.fontFamily).toBe("Roboto");
+
+ act(() => {
+ result.current.setFontFamily("");
+ });
+
+ expect(
+ "fontFamily" in (result.current.currentTheme?.settings ?? {}),
+ ).toBe(false);
+ expect(result.current.isDirty).toBe(true);
+ });
+
+ it("removes fontSize from settings when cleared", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.currentTheme?.settings.fontSize).toBe("14px");
+
+ act(() => {
+ result.current.setFontSize("");
+ });
+
+ expect("fontSize" in (result.current.currentTheme?.settings ?? {})).toBe(
+ false,
+ );
+ expect(result.current.isDirty).toBe(true);
+ });
+ });
+
+ describe("draft mode", () => {
+ it("seeds state from defaults without calling GET", async () => {
+ const { result } = setup("new");
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.currentTheme?.name).toBe("Untitled theme");
+ expect(result.current.isDraft).toBe(true);
+
+ expect(
+ fetchMock.callHistory.calls(/\/api\/embed-theme\/\d+/),
+ ).toHaveLength(0);
+ });
+
+ it("allows saving immediately even without changes", async () => {
+ const { result } = setup("new");
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.canSave).toBe(true);
+ });
+
+ it("reports isDirty only after the user makes a change", async () => {
+ const { result } = setup("new");
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ expect(result.current.isDirty).toBe(false);
+
+ act(() => {
+ result.current.setName("Renamed");
+ });
+
+ expect(result.current.isDirty).toBe(true);
+ });
+
+ it("POSTs a new theme on save", async () => {
+ fetchMock.post("path:/api/embed-theme", {
+ ...TEST_THEME,
+ id: 42,
+ name: "Untitled theme",
+ });
+
+ const { result } = setup("new");
+
+ await waitFor(() => {
+ expect(result.current.currentTheme).not.toBeNull();
+ });
+
+ const saved = await result.current.handleSave();
+
+ expect(saved?.id).toBe(42);
+ expect(fetchMock.callHistory.calls("path:/api/embed-theme")).toHaveLength(
+ 1,
+ );
+ });
+ });
+
+ it("reports isNotFound on API error", async () => {
+ fetchMock.get("path:/api/embed-theme/999", 404);
+
+ const { result } = renderHookWithProviders(
+ () => useEmbeddingThemeEditor(999),
+ {},
+ );
+
+ await waitFor(() => {
+ expect(result.current.isNotFound).toBe(true);
+ });
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.ts b/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.ts
new file mode 100644
index 00000000000..3d3c8b39bff
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.ts
@@ -0,0 +1,32 @@
+import { useEffect, useRef } from "react";
+
+import { useSeedDefaultEmbeddingThemesMutation } from "metabase/api/embedding-theme";
+import { useSetting } from "metabase/common/hooks";
+
+import { useDefaultEmbeddingThemes } from "./use-default-embedding-themes";
+
+/**
+ * Lazily seeds the default `Light` and `Dark` embedding themes on first visit of the themes
+ * listing page. Guarded by the `default-embedding-themes-seeded` setting so that subsequent
+ * visits — including those after an admin has deleted the seeded themes — are no-ops.
+ *
+ * Safe to call unconditionally: the hook fires at most one POST per mount, and the backend
+ * endpoint is itself idempotent and transactional.
+ */
+export function useEnsureDefaultEmbeddingThemes() {
+ const alreadySeeded = useSetting("default-embedding-themes-seeded");
+ const defaultThemes = useDefaultEmbeddingThemes();
+ const [seedDefaultThemes] = useSeedDefaultEmbeddingThemesMutation();
+ const hasAttempted = useRef(false);
+
+ useEffect(() => {
+ // Wait until the setting has resolved — `undefined` means the session has not hydrated yet.
+ // Firing before that would race with the initial setting fetch and trigger a spurious POST.
+ if (alreadySeeded !== false || hasAttempted.current) {
+ return;
+ }
+
+ hasAttempted.current = true;
+ seedDefaultThemes({ themes: defaultThemes });
+ }, [alreadySeeded, defaultThemes, seedDefaultThemes]);
+}
diff --git a/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.unit.spec.tsx b/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.unit.spec.tsx
new file mode 100644
index 00000000000..d1a9ecd351b
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/hooks/use-ensure-default-embedding-themes.unit.spec.tsx
@@ -0,0 +1,95 @@
+import fetchMock from "fetch-mock";
+
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import type { State } from "metabase/redux/store";
+import { createMockState } from "metabase/redux/store/mocks";
+
+import { useEnsureDefaultEmbeddingThemes } from "./use-ensure-default-embedding-themes";
+
+function setup({ alreadySeeded }: { alreadySeeded: boolean }) {
+ fetchMock.post("path:/api/embed-theme/seed-defaults", 204);
+
+ const initialState = createMockState({
+ settings: {
+ values: { "default-embedding-themes-seeded": alreadySeeded },
+ },
+ } as Partial<State>);
+
+ return renderHookWithProviders(() => useEnsureDefaultEmbeddingThemes(), {
+ storeInitialState: initialState,
+ });
+}
+
+describe("useEnsureDefaultEmbeddingThemes", () => {
+ afterEach(() => {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ });
+
+ it("posts default themes once when the setting is not yet seeded", async () => {
+ setup({ alreadySeeded: false });
+
+ await waitFor(() => {
+ const calls = fetchMock.callHistory.calls(
+ "path:/api/embed-theme/seed-defaults",
+ );
+ expect(calls).toHaveLength(1);
+ });
+
+ const [call] = fetchMock.callHistory.calls(
+ "path:/api/embed-theme/seed-defaults",
+ );
+ const body = JSON.parse(call?.options?.body as string);
+ expect(body.themes).toHaveLength(2);
+ expect(body.themes.map((t: { name: string }) => t.name)).toEqual([
+ "Light",
+ "Dark",
+ ]);
+ expect(body.themes[0].settings.colors).toBeDefined();
+ });
+
+ it("does not post when the setting is already true", async () => {
+ const { rerender } = setup({ alreadySeeded: true });
+
+ // give effects a chance to run
+ rerender();
+
+ const calls = fetchMock.callHistory.calls(
+ "path:/api/embed-theme/seed-defaults",
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ it("does not retry on subsequent renders of the same mount", async () => {
+ const { rerender } = setup({ alreadySeeded: false });
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/embed-theme/seed-defaults"),
+ ).toHaveLength(1);
+ });
+
+ rerender();
+ rerender();
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/embed-theme/seed-defaults"),
+ ).toHaveLength(1);
+ });
+
+ it("does not post while the setting has not hydrated", () => {
+ fetchMock.post("path:/api/embed-theme/seed-defaults", 204);
+
+ const initialState = createMockState({
+ settings: { values: {} },
+ } as Partial<State>);
+
+ renderHookWithProviders(() => useEnsureDefaultEmbeddingThemes(), {
+ storeInitialState: initialState,
+ });
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/embed-theme/seed-defaults"),
+ ).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.ts b/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.ts
new file mode 100644
index 00000000000..d6bca8be8bd
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.ts
@@ -0,0 +1,70 @@
+import type {
+ MetabaseColor,
+ MetabaseColors,
+ MetabaseTheme,
+} from "metabase/embedding-sdk/theme";
+import { SDK_TO_MAIN_APP_COLORS_MAPPING } from "metabase/embedding-sdk/theme/embedding-color-palette";
+import { deriveFullMetabaseTheme } from "metabase/ui/colors/derive-theme";
+import { ACCENT_COUNT } from "metabase/ui/colors/palette";
+import type { ColorName } from "metabase/ui/colors/types";
+import type { ColorSettings } from "metabase-types/api/settings";
+
+type ColorScheme = "light" | "dark";
+
+const SDK_COLORS_TO_PERSIST = [
+ "brand",
+ "background",
+ "text-primary",
+ "text-secondary",
+ "text-tertiary",
+ "border",
+ "background-secondary",
+ "filter",
+ "summarize",
+ "positive",
+ "negative",
+ "shadow",
+ "charts",
+] as const satisfies MetabaseColor[];
+
+export const WHITELABEL_CHART_COLOR_NAMES = Array.from(
+ { length: ACCENT_COUNT },
+ (_, i) => `accent${i}` as ColorName,
+);
+
+export function deriveSdkThemeSettings(
+ colorScheme: ColorScheme,
+ whitelabelColors: ColorSettings = {},
+): MetabaseTheme {
+ const sourceColors = deriveFullMetabaseTheme({
+ colorScheme,
+ whitelabelColors,
+ }).colors;
+
+ const mappedColors: MetabaseColors = {};
+
+ for (const sdkColorKey of SDK_COLORS_TO_PERSIST) {
+ if (sdkColorKey === "charts") {
+ mappedColors.charts = WHITELABEL_CHART_COLOR_NAMES.map(
+ (colorName) => whitelabelColors?.[colorName] ?? sourceColors[colorName],
+ );
+
+ continue;
+ }
+
+ const colorKeys = SDK_TO_MAIN_APP_COLORS_MAPPING[sdkColorKey];
+
+ if (colorKeys.length > 0) {
+ for (const colorKey of colorKeys) {
+ const colorValue = sourceColors[colorKey];
+
+ if (colorValue !== undefined) {
+ mappedColors[sdkColorKey] = colorValue;
+ break;
+ }
+ }
+ }
+ }
+
+ return { colors: mappedColors };
+}
diff --git a/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.unit.spec.ts b/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.unit.spec.ts
new file mode 100644
index 00000000000..f135c492cbc
--- /dev/null
+++ b/frontend/src/metabase/admin/embedding/utils/derive-sdk-theme-settings.unit.spec.ts
@@ -0,0 +1,52 @@
+import { deriveSdkThemeSettings } from "./derive-sdk-theme-settings";
+
+describe("deriveSdkThemeSettings", () => {
+ it("produces SDK-shaped colors for the light variant", () => {
+ const theme = deriveSdkThemeSettings("light");
+
+ expect(theme.colors).toBeDefined();
+ expect(typeof theme.colors?.brand).toBe("string");
+ expect(typeof theme.colors?.background).toBe("string");
+ expect(typeof theme.colors?.["text-primary"]).toBe("string");
+ expect(theme.colors?.charts).toHaveLength(8);
+ });
+
+ it("produces a different background for the dark variant than the light variant", () => {
+ const light = deriveSdkThemeSettings("light");
+ const dark = deriveSdkThemeSettings("dark");
+
+ expect(dark.colors?.background).toBeDefined();
+ expect(dark.colors?.background).not.toBe(light.colors?.background);
+ expect(dark.colors?.["text-primary"]).not.toBe(
+ light.colors?.["text-primary"],
+ );
+ });
+
+ it("applies whitelabel overrides on top of the base variant", () => {
+ const theme = deriveSdkThemeSettings("light", {
+ brand: "#8e44ad",
+ filter: "#16a085",
+ summarize: "#d35400",
+ });
+
+ expect(theme.colors?.brand).toBe("#8e44ad");
+ expect(theme.colors?.filter).toBe("#16a085");
+ expect(theme.colors?.summarize).toBe("#d35400");
+ });
+
+ it("applies whitelabel accent colors to the chart palette", () => {
+ const theme = deriveSdkThemeSettings("light", {
+ accent0: "#e74c3c",
+ accent7: "#34495e",
+ });
+
+ expect(theme.colors?.charts?.[0]).toBe("#e74c3c");
+ expect(theme.colors?.charts?.[7]).toBe("#34495e");
+ });
+
+ it("retains whitelabel overrides on the dark variant", () => {
+ const dark = deriveSdkThemeSettings("dark", { brand: "#ff003b" });
+
+ expect(dark.colors?.brand).toBe("#ff003b");
+ });
+});
diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsx
index f173c558a22..74a7aa81476 100644
--- a/frontend/src/metabase/admin/routes.tsx
+++ b/frontend/src/metabase/admin/routes.tsx
@@ -14,6 +14,8 @@ import { DatabasePage } from "metabase/admin/databases/containers/DatabasePage";
import { RevisionHistoryApp } from "metabase/admin/datamodel/containers/RevisionHistoryApp";
import { SegmentApp } from "metabase/admin/datamodel/containers/SegmentApp";
import { SegmentListApp } from "metabase/admin/datamodel/containers/SegmentListApp";
+import { EmbeddingThemeEditorApp } from "metabase/admin/embedding/components/ThemeEditor";
+import { EmbeddingThemeListingApp } from "metabase/admin/embedding/components/ThemeListing";
import { AdminEmbeddingApp } from "metabase/admin/embedding/containers/AdminEmbeddingApp";
import { AdminPeopleApp } from "metabase/admin/people/containers/AdminPeopleApp";
import { EditUserModal } from "metabase/admin/people/containers/EditUserModal";
@@ -205,6 +207,8 @@ export const getRoutes = (
)}
<Route path="security" component={EmbeddingSecuritySettings} />
+ <Route path="themes" component={EmbeddingThemeListingApp} />
+ <Route path="themes/:themeId" component={EmbeddingThemeEditorApp} />
</Route>
</Route>
diff --git a/frontend/src/metabase/admin/upsells/UpsellEmbeddingTheme.tsx b/frontend/src/metabase/admin/upsells/UpsellEmbeddingTheme.tsx
new file mode 100644
index 00000000000..7a9dfd537e3
--- /dev/null
+++ b/frontend/src/metabase/admin/upsells/UpsellEmbeddingTheme.tsx
@@ -0,0 +1,42 @@
+import { t } from "ttag";
+
+import { DottedBackground } from "metabase/common/components/upsells/components/DottedBackground";
+import { LineDecorator } from "metabase/common/components/upsells/components/LineDecorator";
+import { useUpgradeAction } from "metabase/common/components/upsells/components/UpgradeModal";
+import { UpsellCardContent } from "metabase/common/components/upsells/components/UpsellCardContent";
+import { UPGRADE_URL } from "metabase/common/components/upsells/constants";
+import { useHasTokenFeature } from "metabase/common/hooks";
+import { Stack } from "metabase/ui";
+
+export const UpsellEmbeddingTheme = ({ source }: { source: string }) => {
+ const hasSimpleEmbedding = useHasTokenFeature("embedding_simple");
+ const campaign = "embedding-themes";
+
+ const { onClick: upgradeOnClick, url: upgradeUrl } = useUpgradeAction({
+ url: UPGRADE_URL,
+ campaign,
+ location: source,
+ });
+
+ if (hasSimpleEmbedding) {
+ return null;
+ }
+
+ return (
+ <DottedBackground px="3.5rem" pb="2rem">
+ <Stack align="center" p={40}>
+ <LineDecorator>
+ <UpsellCardContent
+ campaign={campaign}
+ location={source}
+ title={t`Create custom themes`}
+ description={t`Fine-tune the appearance of your embedded content with colors and fonts.`}
+ upgradeOnClick={upgradeOnClick}
+ upgradeUrl={upgradeUrl}
+ image="app/assets/img/upsell-themes.png"
+ />
+ </LineDecorator>
+ </Stack>
+ </DottedBackground>
+ );
+};
diff --git a/frontend/src/metabase/admin/upsells/index.ts b/frontend/src/metabase/admin/upsells/index.ts
index a35c000422c..1d0b93042e1 100644
--- a/frontend/src/metabase/admin/upsells/index.ts
+++ b/frontend/src/metabase/admin/upsells/index.ts
@@ -2,6 +2,7 @@ export * from "./UpsellBetterSupport";
export * from "./UpsellCacheConfig";
export * from "./UpsellCloud";
export * from "./UpsellEmailWhitelabel";
+export * from "./UpsellEmbeddingTheme";
export * from "./UpsellHosting";
export * from "./UpsellPerformanceTools";
export * from "./UpsellPermissions";
diff --git a/frontend/src/metabase/api/embedding-theme.ts b/frontend/src/metabase/api/embedding-theme.ts
new file mode 100644
index 00000000000..7953e993b17
--- /dev/null
+++ b/frontend/src/metabase/api/embedding-theme.ts
@@ -0,0 +1,93 @@
+import type {
+ CreateEmbeddingThemeRequest,
+ EmbeddingTheme,
+ SeedDefaultEmbeddingThemesRequest,
+ UpdateEmbeddingThemeRequest,
+} from "metabase-types/api";
+
+import { Api } from "./api";
+import { idTag, invalidateTags, listTag, tag } from "./tags";
+
+export const embeddingThemeApi = Api.injectEndpoints({
+ endpoints: (builder) => ({
+ listEmbeddingThemes: builder.query<EmbeddingTheme[], void>({
+ query: () => `/api/embed-theme`,
+ providesTags: (themes) =>
+ themes
+ ? [
+ ...themes.map((theme) => idTag("embed-theme", theme.id)),
+ listTag("embed-theme"),
+ ]
+ : [listTag("embed-theme")],
+ }),
+ getEmbeddingTheme: builder.query<EmbeddingTheme, number>({
+ query: (id) => `/api/embed-theme/${id}`,
+ providesTags: (_, __, id) => [idTag("embed-theme", id)],
+ }),
+ createEmbeddingTheme: builder.mutation<
+ EmbeddingTheme,
+ CreateEmbeddingThemeRequest
+ >({
+ query: (body) => ({
+ method: "POST",
+ url: `/api/embed-theme`,
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("embed-theme")]),
+ }),
+ updateEmbeddingTheme: builder.mutation<
+ EmbeddingTheme,
+ UpdateEmbeddingThemeRequest
+ >({
+ query: ({ id, ...body }) => ({
+ method: "PUT",
+ url: `/api/embed-theme/${id}`,
+ body,
+ }),
+ invalidatesTags: (_, error, { id }) =>
+ invalidateTags(error, [
+ listTag("embed-theme"),
+ idTag("embed-theme", id),
+ ]),
+ }),
+ deleteEmbeddingTheme: builder.mutation<void, number>({
+ query: (id) => ({ method: "DELETE", url: `/api/embed-theme/${id}` }),
+ invalidatesTags: (_, error, id) =>
+ invalidateTags(error, [
+ listTag("embed-theme"),
+ idTag("embed-theme", id),
+ ]),
+ }),
+ copyEmbeddingTheme: builder.mutation<EmbeddingTheme, number>({
+ query: (id) => ({ method: "POST", url: `/api/embed-theme/${id}/copy` }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("embed-theme")]),
+ }),
+ seedDefaultEmbeddingThemes: builder.mutation<
+ void,
+ SeedDefaultEmbeddingThemesRequest
+ >({
+ query: (body) => ({
+ method: "POST",
+ url: `/api/embed-theme/seed-defaults`,
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [
+ listTag("embed-theme"),
+ tag("session-properties"),
+ ]),
+ }),
+ }),
+});
+
+export const {
+ useListEmbeddingThemesQuery,
+ useGetEmbeddingThemeQuery,
+ useCreateEmbeddingThemeMutation,
+ useUpdateEmbeddingThemeMutation,
+ useDeleteEmbeddingThemeMutation,
+ useCopyEmbeddingThemeMutation,
+ useSeedDefaultEmbeddingThemesMutation,
+} = embeddingThemeApi;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 200ea6b21d6..f80a114cc2d 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -17,6 +17,7 @@ export const TAG_TYPES = [
"database",
"dataset",
"document",
+ "embed-theme",
"external-transform",
"public-document",
"comment",
diff --git a/frontend/src/metabase/common/components/ColorPicker/ColorPicker.unit.spec.tsx b/frontend/src/metabase/common/components/ColorPicker/ColorPicker.unit.spec.tsx
index 38bd93a3127..f3cfef26c5c 100644
--- a/frontend/src/metabase/common/components/ColorPicker/ColorPicker.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/ColorPicker/ColorPicker.unit.spec.tsx
@@ -5,6 +5,7 @@ import { useState } from "react";
import { render, screen, within } from "__support__/ui";
import { ColorPicker } from "./ColorPicker";
+import { ColorPickerContent } from "./ColorPickerContent";
const TestColorPicker = () => {
const [value, setValue] = useState("white");
@@ -37,4 +38,61 @@ describe("ColorPicker", () => {
expect(screen.getByLabelText(color.hex())).toBeInTheDocument();
});
+
+ describe("ColorPickerContent showAlpha", () => {
+ it("does not render the alpha percentage input by default", () => {
+ render(<ColorPickerContent value="#ff0000" onChange={jest.fn()} />);
+ expect(
+ screen.queryByRole("textbox", { name: "Alpha percentage" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders the alpha percentage input when showAlpha is set", () => {
+ render(
+ <ColorPickerContent value="#ff0000" showAlpha onChange={jest.fn()} />,
+ );
+ const percentInput = screen.getByRole("textbox", {
+ name: "Alpha percentage",
+ });
+ expect(percentInput).toHaveValue("100");
+ });
+
+ it("reflects the alpha from an 8-character hex value", () => {
+ render(
+ <ColorPickerContent value="#ff000080" showAlpha onChange={jest.fn()} />,
+ );
+ const percentInput = screen.getByRole("textbox", {
+ name: "Alpha percentage",
+ });
+ expect(percentInput).toHaveValue("50");
+ });
+
+ it("emits an 8-character hex when alpha is reduced via the percentage input", async () => {
+ const onChange = jest.fn();
+ render(
+ <ColorPickerContent value="#ff0000" showAlpha onChange={onChange} />,
+ );
+
+ const percentInput = screen.getByRole("textbox", {
+ name: "Alpha percentage",
+ });
+ await userEvent.clear(percentInput);
+ await userEvent.type(percentInput, "50");
+
+ expect(onChange).toHaveBeenLastCalledWith("#ff000080");
+ });
+
+ it("preserves alpha when the hex input is edited", async () => {
+ const onChange = jest.fn();
+ render(
+ <ColorPickerContent value="#ff000080" showAlpha onChange={onChange} />,
+ );
+
+ const [hexInput] = screen.getAllByRole("textbox");
+ await userEvent.clear(hexInput);
+ await userEvent.type(hexInput, "#00ff00");
+
+ expect(onChange).toHaveBeenLastCalledWith("#00ff0080");
+ });
+ });
});
diff --git a/frontend/src/metabase/common/components/ColorPicker/ColorPickerContent.tsx b/frontend/src/metabase/common/components/ColorPicker/ColorPickerContent.tsx
index 21327b8ac05..e1486857eb4 100644
--- a/frontend/src/metabase/common/components/ColorPicker/ColorPickerContent.tsx
+++ b/frontend/src/metabase/common/components/ColorPicker/ColorPickerContent.tsx
@@ -1,8 +1,11 @@
+import Color from "color";
import type { HTMLAttributes, Ref } from "react";
-import { forwardRef, useCallback } from "react";
+import { forwardRef, useCallback, useMemo } from "react";
import type { ColorState } from "react-color";
+import { t } from "ttag";
import { ColorInput } from "metabase/common/components/ColorInput";
+import { Group, NumberInput } from "metabase/ui";
import { ContentContainer } from "./ColorPicker.styled";
import { ColorPickerControls } from "./ColorPickerControls";
@@ -14,22 +17,92 @@ export type ColorPickerContentAttributes = Omit<
export interface ColorPickerContentProps extends ColorPickerContentAttributes {
value?: string;
+ showAlpha?: boolean;
onChange?: (value?: string) => void;
}
export const ColorPickerContent = forwardRef(function ColorPickerContent(
- { value, onChange, ...props }: ColorPickerContentProps,
+ { value, showAlpha, onChange, ...props }: ColorPickerContentProps,
ref: Ref<HTMLDivElement>,
) {
- const handleChange = useCallback(
- (state: ColorState) => onChange?.(state.hex),
- [onChange],
+ const alpha = useMemo(() => getAlpha(value), [value]);
+
+ const handlePickerChange = useCallback(
+ (state: ColorState) => {
+ const newAlpha = state.rgb.a ?? 1;
+ onChange?.(buildHex(state.hex, showAlpha ? newAlpha : 1));
+ },
+ [onChange, showAlpha],
+ );
+
+ const handleHexChange = useCallback(
+ (newHex?: string) => {
+ if (!showAlpha || !newHex) {
+ onChange?.(newHex);
+ return;
+ }
+ onChange?.(buildHex(newHex, alpha));
+ },
+ [onChange, showAlpha, alpha],
+ );
+
+ const handleAlphaPercentChange = useCallback(
+ (percent: string | number) => {
+ const baseHex = getBaseHex(value);
+ if (!baseHex) {
+ return;
+ }
+ const parsed =
+ typeof percent === "number" ? percent : parseFloat(percent);
+ if (!Number.isFinite(parsed)) {
+ return;
+ }
+ const clamped = Math.max(0, Math.min(100, parsed));
+ onChange?.(buildHex(baseHex, clamped / 100));
+ },
+ [onChange, value],
);
return (
<ContentContainer {...props} ref={ref}>
- <ColorPickerControls color={value} onChange={handleChange} />
- <ColorInput value={value} fullWidth onChange={onChange} />
+ <ColorPickerControls color={value} onChange={handlePickerChange} />
+ {showAlpha ? (
+ <Group gap="sm" wrap="nowrap" align="flex-start">
+ <ColorInput value={value} fullWidth onChange={handleHexChange} />
+ <NumberInput
+ aria-label={t`Alpha percentage`}
+ value={Math.round(alpha * 100)}
+ onChange={handleAlphaPercentChange}
+ min={0}
+ max={100}
+ w="6rem"
+ rightSection="%"
+ hideControls
+ />
+ </Group>
+ ) : (
+ <ColorInput value={value} fullWidth onChange={onChange} />
+ )}
</ContentContainer>
);
});
+
+const getAlpha = (value?: string): number => {
+ try {
+ return value ? Color(value).alpha() : 1;
+ } catch {
+ return 1;
+ }
+};
+
+const getBaseHex = (value?: string): string | undefined => {
+ try {
+ return value ? Color(value).hex() : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const buildHex = (hex: string, alpha: number): string => {
+ return Color(hex).alpha(alpha).hexa().toLowerCase();
+};
diff --git a/frontend/src/metabase/data-studio/upsells/components/DottedBackground/DottedBackground.module.css b/frontend/src/metabase/common/components/upsells/components/DottedBackground/DottedBackground.module.css
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/DottedBackground/DottedBackground.module.css
rename to frontend/src/metabase/common/components/upsells/components/DottedBackground/DottedBackground.module.css
diff --git a/frontend/src/metabase/data-studio/upsells/components/DottedBackground/DottedBackground.tsx b/frontend/src/metabase/common/components/upsells/components/DottedBackground/DottedBackground.tsx
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/DottedBackground/DottedBackground.tsx
rename to frontend/src/metabase/common/components/upsells/components/DottedBackground/DottedBackground.tsx
diff --git a/frontend/src/metabase/data-studio/upsells/components/DottedBackground/index.ts b/frontend/src/metabase/common/components/upsells/components/DottedBackground/index.ts
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/DottedBackground/index.ts
rename to frontend/src/metabase/common/components/upsells/components/DottedBackground/index.ts
diff --git a/frontend/src/metabase/data-studio/upsells/components/LineDecorator/LineDecorator.module.css b/frontend/src/metabase/common/components/upsells/components/LineDecorator/LineDecorator.module.css
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/LineDecorator/LineDecorator.module.css
rename to frontend/src/metabase/common/components/upsells/components/LineDecorator/LineDecorator.module.css
diff --git a/frontend/src/metabase/data-studio/upsells/components/LineDecorator/LineDecorator.tsx b/frontend/src/metabase/common/components/upsells/components/LineDecorator/LineDecorator.tsx
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/LineDecorator/LineDecorator.tsx
rename to frontend/src/metabase/common/components/upsells/components/LineDecorator/LineDecorator.tsx
diff --git a/frontend/src/metabase/data-studio/upsells/components/LineDecorator/index.ts b/frontend/src/metabase/common/components/upsells/components/LineDecorator/index.ts
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/LineDecorator/index.ts
rename to frontend/src/metabase/common/components/upsells/components/LineDecorator/index.ts
diff --git a/frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.module.css b/frontend/src/metabase/common/components/upsells/components/UpsellCardContent.module.css
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.module.css
rename to frontend/src/metabase/common/components/upsells/components/UpsellCardContent.module.css
diff --git a/frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.tsx b/frontend/src/metabase/common/components/upsells/components/UpsellCardContent.tsx
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.tsx
rename to frontend/src/metabase/common/components/upsells/components/UpsellCardContent.tsx
diff --git a/frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.unit.spec.tsx b/frontend/src/metabase/common/components/upsells/components/UpsellCardContent.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/data-studio/upsells/components/UpsellCardContent.unit.spec.tsx
rename to frontend/src/metabase/common/components/upsells/components/UpsellCardContent.unit.spec.tsx
diff --git a/frontend/src/metabase/data-studio/upsells/pages/BaseUpsellPage.tsx b/frontend/src/metabase/data-studio/upsells/pages/BaseUpsellPage.tsx
index a33c2c501f9..a0b2cf1d5d3 100644
--- a/frontend/src/metabase/data-studio/upsells/pages/BaseUpsellPage.tsx
+++ b/frontend/src/metabase/data-studio/upsells/pages/BaseUpsellPage.tsx
@@ -1,13 +1,12 @@
+import { DottedBackground } from "metabase/common/components/upsells/components/DottedBackground";
+import { LineDecorator } from "metabase/common/components/upsells/components/LineDecorator";
import { useUpgradeAction } from "metabase/common/components/upsells/components/UpgradeModal";
+import { UpsellCardContent } from "metabase/common/components/upsells/components/UpsellCardContent";
import { DATA_STUDIO_UPGRADE_URL } from "metabase/common/components/upsells/constants";
import { DataStudioBreadcrumbs } from "metabase/data-studio/common/components/DataStudioBreadcrumbs";
import { PaneHeader } from "metabase/data-studio/common/components/PaneHeader";
-import { UpsellCardContent } from "metabase/data-studio/upsells/components/UpsellCardContent";
import { Stack } from "metabase/ui";
-import { DottedBackground } from "../components/DottedBackground";
-import { LineDecorator } from "../components/LineDecorator";
-
import S from "./BaseUpsellPage.module.css";
export type BaseUpsellPageProps = {
diff --git a/frontend/src/metabase/data-studio/upsells/pages/RemoteSyncUpsellPage.tsx b/frontend/src/metabase/data-studio/upsells/pages/RemoteSyncUpsellPage.tsx
index ffd672a9193..e085dd0f0df 100644
--- a/frontend/src/metabase/data-studio/upsells/pages/RemoteSyncUpsellPage.tsx
+++ b/frontend/src/metabase/data-studio/upsells/pages/RemoteSyncUpsellPage.tsx
@@ -1,17 +1,16 @@
import { t } from "ttag";
+import { DottedBackground } from "metabase/common/components/upsells/components/DottedBackground";
+import { LineDecorator } from "metabase/common/components/upsells/components/LineDecorator";
import { useUpgradeAction } from "metabase/common/components/upsells/components/UpgradeModal";
+import { UpsellCardContent } from "metabase/common/components/upsells/components/UpsellCardContent";
import { DATA_STUDIO_UPGRADE_URL } from "metabase/common/components/upsells/constants";
import { DataStudioBreadcrumbs } from "metabase/data-studio/common/components/DataStudioBreadcrumbs";
import { PaneHeader } from "metabase/data-studio/common/components/PaneHeader";
-import { UpsellCardContent } from "metabase/data-studio/upsells/components/UpsellCardContent";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Stack } from "metabase/ui";
-import { DottedBackground } from "../components/DottedBackground";
-import { LineDecorator } from "../components/LineDecorator";
-
const CAMPAIGN = "remote-sync";
const LOCATION = "data-studio-remote-sync";
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/BaseAppearanceSection.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/BaseAppearanceSection.tsx
index fd3936afa81..60d0f89d28f 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/BaseAppearanceSection.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/BaseAppearanceSection.tsx
@@ -5,18 +5,22 @@ import { Flex, Group, Text } from "metabase/ui";
type Props = {
icons?: ReactNode;
+ noTitle?: boolean;
};
export const BaseAppearanceSection = ({
children,
icons,
+ noTitle,
}: PropsWithChildren<Props>) => {
return (
<Flex direction="column" data-testid="appearance-section">
- <Group justify="space-between" align="center" mb="lg">
- <Text size="lg" fw="bold">
- {t`Appearance`}
- </Text>
+ <Group justify="space-between" align="center" mb="md">
+ {noTitle ? null : (
+ <Text size="lg" fw="bold">
+ {t`Appearance`}
+ </Text>
+ )}
<Flex gap="md" align="center">
{icons}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ColorCustomizationSection.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ColorCustomizationSection.tsx
index a6bddba0f04..cb6c91b6fb7 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ColorCustomizationSection.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ColorCustomizationSection.tsx
@@ -1,16 +1,14 @@
-import { useCallback, useState } from "react";
-import { t } from "ttag";
+import { useEffect, useState } from "react";
+import { usePrevious } from "react-use";
import { ColorPillPicker } from "metabase/common/components/ColorPicker";
import { useSetting } from "metabase/common/hooks";
import type { MetabaseColors } from "metabase/embedding-sdk/theme";
-import { ActionIcon, Icon, Stack, Text, Tooltip } from "metabase/ui";
+import { Group, Stack, Text } from "metabase/ui";
import { originalColors, staticVizOverrides } from "metabase/ui/colors";
import { getConfigurableThemeColors } from "../../utils/theme-colors";
-import { BaseAppearanceSection } from "./BaseAppearanceSection";
-
const defaultMetabaseColorsWithoutAlpha = {
...originalColors,
...staticVizOverrides,
@@ -19,13 +17,11 @@ const defaultMetabaseColorsWithoutAlpha = {
interface ColorCustomizationSectionProps {
theme?: { colors?: Partial<MetabaseColors> };
onColorChange: (colors: Partial<MetabaseColors>) => void;
- onColorReset?: () => void;
}
export const ColorCustomizationSection = ({
theme,
onColorChange,
- onColorReset,
}: ColorCustomizationSectionProps) => {
const applicationColors = useSetting("application-colors");
@@ -34,34 +30,16 @@ export const ColorCustomizationSection = ({
Record<string, string>
>({});
- const resetColors = useCallback(() => {
- setColorPreviewValues({});
- onColorReset?.();
- }, [onColorReset]);
-
- // If some of the colors are set, then `theme.colors` would be no longer empty.
- // This also matches when the `theme` key is shown in the code snippets.
- const hasColorChanged = !!theme?.colors;
+ // Clear preview values when theme colors are reset externally.
+ const prevColors = usePrevious(theme?.colors);
+ useEffect(() => {
+ if (prevColors && !theme?.colors) {
+ setColorPreviewValues({});
+ }
+ }, [theme?.colors, prevColors]);
return (
- <BaseAppearanceSection
- icons={
- <>
- {hasColorChanged && (
- <Tooltip label={t`Reset colors`}>
- <ActionIcon
- variant="subtle"
- size="sm"
- onClick={resetColors}
- aria-label={t`Reset colors`}
- >
- <Icon name="revert" c="brand" />
- </ActionIcon>
- </Tooltip>
- )}
- </>
- }
- >
+ <Group align="start" gap="xl">
{getConfigurableThemeColors().map(({ key, name, originalColorKey }) => {
// Use the default from appearance settings. If not set, use the default Metabase color.
const originalColor =
@@ -88,6 +66,6 @@ export const ColorCustomizationSection = ({
</Stack>
);
})}
- </BaseAppearanceSection>
+ </Group>
);
};
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/SimpleThemeSwitcherSection.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/SimpleThemeSwitcherSection.tsx
index 04eb942d44a..f5eaedadcec 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/SimpleThemeSwitcherSection.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/SimpleThemeSwitcherSection.tsx
@@ -3,8 +3,6 @@ import { t } from "ttag";
import type { MetabaseThemePreset } from "metabase/embedding-sdk/theme";
import { Radio, Stack } from "metabase/ui";
-import { BaseAppearanceSection } from "./BaseAppearanceSection";
-
type Props = {
preset: MetabaseThemePreset | undefined;
onPresetChange: (themePreset: MetabaseThemePreset) => void;
@@ -15,16 +13,14 @@ export const SimpleThemeSwitcherSection = ({
onPresetChange,
}: Props) => {
return (
- <BaseAppearanceSection>
- <Radio.Group
- value={preset}
- onChange={(value) => onPresetChange(value as MetabaseThemePreset)}
- >
- <Stack gap="sm">
- <Radio value="light" label={t`Light`} />
- <Radio value="dark" label={t`Dark`} />
- </Stack>
- </Radio.Group>
- </BaseAppearanceSection>
+ <Radio.Group
+ value={preset}
+ onChange={(value) => onPresetChange(value as MetabaseThemePreset)}
+ >
+ <Stack gap="sm">
+ <Radio value="light" label={t`Light`} />
+ <Radio value="dark" label={t`Dark`} />
+ </Stack>
+ </Radio.Group>
);
};
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.module.css b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.module.css
new file mode 100644
index 00000000000..ab05d8d6726
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.module.css
@@ -0,0 +1,23 @@
+.card {
+ border: 1px solid var(--mb-color-border);
+ padding: 8px;
+ min-width: 120px;
+ flex: 1;
+}
+
+.cardSelected {
+ border: 2px solid var(--mb-color-brand);
+ padding: 7px;
+}
+
+.colorBar {
+ border-radius: 3px;
+ overflow: hidden;
+ border: 1px solid #eee;
+}
+
+.colorSegment {
+ flex: 1;
+ height: 5px;
+ min-width: 8px;
+}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.tsx
new file mode 100644
index 00000000000..11285d46589
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeCard.tsx
@@ -0,0 +1,69 @@
+import cx from "classnames";
+import type { ReactNode } from "react";
+
+import type { MetabaseColors } from "metabase/embedding-sdk/theme";
+import { Box, Group, Stack, Text, UnstyledButton } from "metabase/ui";
+
+import S from "./ThemeCard.module.css";
+
+export function getThemeColors(colors?: Partial<MetabaseColors>): string[] {
+ return [
+ colors?.brand ?? "var(--mb-color-brand)",
+ colors?.["text-primary"] ?? "var(--mb-color-text-primary)",
+ colors?.background ?? "var(--mb-color-background)",
+ ];
+}
+
+export function ThemeCard({
+ name,
+ colors,
+ fontFamily,
+ icon,
+ isSelected,
+ onClick,
+}: {
+ name: string;
+ colors: string[];
+ fontFamily?: string;
+ icon?: ReactNode;
+ isSelected: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <UnstyledButton
+ onClick={onClick}
+ data-testid={`theme-card-${name}`}
+ data-selected={isSelected}
+ className={cx(S.card, isSelected && S.cardSelected)}
+ bdrs="md"
+ h="42px"
+ >
+ <Stack gap="xs">
+ <Group gap={4} justify="space-between" wrap="nowrap">
+ <Text
+ size="xs"
+ h={12}
+ fw={500}
+ style={{ fontFamily }}
+ truncate
+ title={name}
+ >
+ {name}
+ </Text>
+ {icon}
+ </Group>
+ {colors.length > 0 && (
+ <Group gap={0} justify="center" className={S.colorBar}>
+ {colors.map((color, index) => (
+ <Box
+ key={index}
+ className={S.colorSegment}
+ style={{ backgroundColor: String(color) }}
+ />
+ ))}
+ </Group>
+ )}
+ </Stack>
+ </UnstyledButton>
+ );
+}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.tsx
new file mode 100644
index 00000000000..1c46d11a72d
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.tsx
@@ -0,0 +1,146 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import type { MetabaseColors } from "metabase/embedding-sdk/theme";
+import { Box, Flex, Icon, SimpleGrid, Tooltip } from "metabase/ui";
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import type { SdkIframeEmbedSetupTheme } from "../../types";
+
+import { ColorCustomizationSection } from "./ColorCustomizationSection";
+import { ThemeCard, getThemeColors } from "./ThemeCard";
+
+type ThemeSelection =
+ | { type: "default" }
+ | { type: "saved"; themeId: number }
+ | { type: "custom" };
+
+interface ThemeSelectorSectionProps {
+ savedThemes: EmbeddingTheme[];
+ theme: SdkIframeEmbedSetupTheme | undefined;
+ onThemeChange: (themeId: number | undefined) => void;
+ onColorChange: (colors: Partial<MetabaseColors>) => void;
+ onColorReset: () => void;
+}
+
+export const ThemeSelectorSection = ({
+ savedThemes,
+ theme,
+ onThemeChange,
+ onColorChange,
+ onColorReset,
+}: ThemeSelectorSectionProps) => {
+ const [selection, setSelection] = useState<ThemeSelection>(() => {
+ const themeId = theme?.id;
+ const isKnown =
+ themeId !== undefined && savedThemes.some((t) => t.id === themeId);
+ if (isKnown) {
+ return { type: "saved", themeId };
+ }
+ if (theme?.colors) {
+ return { type: "custom" };
+ }
+ return { type: "default" };
+ });
+
+ const isCustomSelected = selection.type === "custom";
+
+ const handleDefaultClick = () => {
+ setSelection({ type: "default" });
+ onThemeChange(undefined);
+ };
+
+ const handleThemeCardClick = (themeId: number) => {
+ if (!savedThemes.some((t) => t.id === themeId)) {
+ return;
+ }
+
+ setSelection({ type: "saved", themeId });
+ onThemeChange(themeId);
+ };
+
+ const handleCustomClick = () => {
+ setSelection({ type: "custom" });
+ onThemeChange(undefined);
+ };
+
+ const hasThemes = savedThemes.length > 0;
+ const showColorInputs = !hasThemes || isCustomSelected;
+ const hasColorChanged = !!theme?.colors;
+
+ const handleResetColors = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ onColorReset();
+ };
+
+ const customCardIcon = hasColorChanged ? (
+ <Tooltip label={t`Reset colors`}>
+ <Icon
+ name="revert"
+ size={12}
+ c="brand"
+ onClick={handleResetColors}
+ aria-label={t`Reset colors`}
+ style={{ cursor: "pointer" }}
+ />
+ </Tooltip>
+ ) : (
+ <Icon name="pencil" size={12} c="text-secondary" />
+ );
+
+ return (
+ <Flex direction="column" gap={0} w="100%">
+ {hasThemes && (
+ <SimpleGrid cols={2} spacing="sm">
+ <ThemeCard
+ name={t`Instance theme`}
+ colors={[]}
+ icon={
+ <Tooltip
+ label={t`Changing the appearance settings will also update this embed.`}
+ >
+ <Icon
+ name="info"
+ size={12}
+ c="text-secondary"
+ aria-label={t`Instance theme info`}
+ />
+ </Tooltip>
+ }
+ isSelected={selection.type === "default"}
+ onClick={handleDefaultClick}
+ />
+ {savedThemes.map((savedTheme) => (
+ <ThemeCard
+ key={savedTheme.id}
+ name={savedTheme.name}
+ colors={getThemeColors(savedTheme.settings.colors)}
+ fontFamily={savedTheme.settings.fontFamily}
+ isSelected={
+ selection?.type === "saved" &&
+ selection.themeId === savedTheme.id
+ }
+ onClick={() => handleThemeCardClick(savedTheme.id)}
+ />
+ ))}
+ <ThemeCard
+ name={t`Custom`}
+ colors={[]}
+ icon={customCardIcon}
+ isSelected={isCustomSelected}
+ onClick={handleCustomClick}
+ />
+ </SimpleGrid>
+ )}
+
+ {isCustomSelected && <Box h={24} />}
+
+ {showColorInputs && (
+ <ColorCustomizationSection
+ theme={theme}
+ onColorChange={onColorChange}
+ />
+ )}
+ </Flex>
+ );
+};
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.unit.spec.tsx
new file mode 100644
index 00000000000..480adb612c9
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/Appearance/ThemeSelectorSection.unit.spec.tsx
@@ -0,0 +1,238 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen, within } from "__support__/ui";
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import { ThemeSelectorSection } from "./ThemeSelectorSection";
+
+const SAVED_THEMES: EmbeddingTheme[] = [
+ {
+ id: 1,
+ name: "Dark Theme",
+ settings: {
+ colors: {
+ brand: "#BB86FC",
+ "text-primary": "#FFFFFF",
+ background: "#121212",
+ },
+ fontFamily: "Inter",
+ },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ },
+ {
+ id: 2,
+ name: "Ocean Theme",
+ settings: {
+ colors: {
+ brand: "#0077B6",
+ "text-primary": "#023E8A",
+ background: "#CAF0F8",
+ },
+ },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ },
+];
+
+function setup({
+ savedThemes = SAVED_THEMES,
+ theme = undefined,
+ onThemeChange = jest.fn(),
+ onColorChange = jest.fn(),
+ onColorReset = jest.fn(),
+}: {
+ savedThemes?: EmbeddingTheme[];
+ theme?: Parameters<typeof ThemeSelectorSection>[0]["theme"];
+ onThemeChange?: jest.Mock;
+ onColorChange?: jest.Mock;
+ onColorReset?: jest.Mock;
+} = {}) {
+ const utils = renderWithProviders(
+ <ThemeSelectorSection
+ savedThemes={savedThemes}
+ theme={theme}
+ onThemeChange={onThemeChange}
+ onColorChange={onColorChange}
+ onColorReset={onColorReset}
+ />,
+ );
+
+ return { ...utils, onThemeChange, onColorChange, onColorReset };
+}
+
+describe("ThemeSelectorSection", () => {
+ describe("with saved themes", () => {
+ it("renders Instance theme, saved theme cards, and a Custom card", () => {
+ setup();
+
+ expect(screen.getByText("Instance theme")).toBeInTheDocument();
+ expect(screen.getByText("Dark Theme")).toBeInTheDocument();
+ expect(screen.getByText("Ocean Theme")).toBeInTheDocument();
+ expect(screen.getByText("Custom")).toBeInTheDocument();
+ });
+
+ it("renders an info icon with tooltip on the Instance theme card", async () => {
+ setup();
+
+ const infoIcon = within(
+ screen.getByTestId("theme-card-Instance theme"),
+ ).getByLabelText("Instance theme info");
+ expect(infoIcon).toBeInTheDocument();
+
+ await userEvent.hover(infoIcon);
+
+ expect(
+ await screen.findByText(
+ "Changing the appearance settings will also update this embed.",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("selects Instance theme by default and sets no theme", async () => {
+ const { onThemeChange } = setup();
+
+ // No theme change should have been called on initial render
+ expect(onThemeChange).not.toHaveBeenCalled();
+
+ // Instance theme card should be rendered
+ expect(
+ screen.getByTestId("theme-card-Instance theme"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not show color inputs by default", () => {
+ setup();
+
+ expect(screen.queryByText("Brand color")).not.toBeInTheDocument();
+ });
+
+ it("passes the theme id when a saved theme card is clicked", async () => {
+ const { onThemeChange } = setup();
+
+ await userEvent.click(screen.getByTestId("theme-card-Dark Theme"));
+
+ expect(onThemeChange).toHaveBeenCalledTimes(1);
+ expect(onThemeChange).toHaveBeenCalledWith(1);
+ });
+
+ it("clears theme when clicking Instance theme after a saved theme", async () => {
+ const { onThemeChange } = setup();
+
+ await userEvent.click(screen.getByTestId("theme-card-Dark Theme"));
+ await userEvent.click(screen.getByTestId("theme-card-Instance theme"));
+
+ expect(onThemeChange).toHaveBeenLastCalledWith(undefined);
+ });
+
+ it("pre-selects the saved theme card matching theme.id on mount", () => {
+ setup({ theme: { id: 2 } });
+
+ expect(screen.getByTestId("theme-card-Ocean Theme")).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ expect(screen.getByTestId("theme-card-Instance theme")).toHaveAttribute(
+ "data-selected",
+ "false",
+ );
+ });
+
+ it("falls back to Instance theme when theme.id does not match any saved theme", () => {
+ setup({ theme: { id: 999 } });
+
+ expect(screen.getByTestId("theme-card-Instance theme")).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ });
+
+ it("pre-selects the Custom card on mount when theme has inline colors but no id", () => {
+ setup({ theme: { colors: { brand: "#FF0000" } } });
+
+ expect(screen.getByTestId("theme-card-Custom")).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ expect(screen.getByTestId("theme-card-Instance theme")).toHaveAttribute(
+ "data-selected",
+ "false",
+ );
+ expect(screen.getByText("Brand color")).toBeInTheDocument();
+ });
+
+ it("shows color inputs when Custom card is clicked", async () => {
+ setup();
+
+ await userEvent.click(screen.getByTestId("theme-card-Custom"));
+
+ expect(screen.getByText("Brand color")).toBeInTheDocument();
+ expect(screen.getByText("Text color")).toBeInTheDocument();
+ expect(screen.getByText("Background color")).toBeInTheDocument();
+ });
+
+ it("hides color inputs when switching from Custom to Instance theme", async () => {
+ setup();
+
+ await userEvent.click(screen.getByTestId("theme-card-Custom"));
+ expect(screen.getByText("Brand color")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("theme-card-Instance theme"));
+ expect(screen.queryByText("Brand color")).not.toBeInTheDocument();
+ });
+
+ it("shows pencil icon on Custom card when no colors are set", () => {
+ setup({ theme: undefined });
+
+ const editButton = within(
+ screen.getByTestId("theme-card-Custom"),
+ ).getByLabelText(`pencil icon`);
+
+ expect(editButton).toBeInTheDocument();
+ });
+
+ it("shows revert icon on Custom card when colors are set", () => {
+ setup({ theme: { colors: { brand: "#FF0000" } } });
+
+ expect(screen.getByLabelText("Reset colors")).toBeInTheDocument();
+ });
+
+ it("calls onColorReset when revert icon is clicked", async () => {
+ const { onColorReset } = setup({
+ theme: { colors: { brand: "#FF0000" } },
+ });
+
+ await userEvent.click(screen.getByLabelText("Reset colors"));
+
+ expect(onColorReset).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not toggle Custom card when revert icon is clicked", async () => {
+ const { onThemeChange } = setup({
+ theme: { colors: { brand: "#FF0000" } },
+ });
+
+ // First select Custom
+ await userEvent.click(screen.getByTestId("theme-card-Custom"));
+ onThemeChange.mockClear();
+
+ // Click the revert icon — should NOT deselect custom
+ await userEvent.click(screen.getByLabelText("Reset colors"));
+
+ // onThemeChange should not have been called (stopPropagation)
+ expect(onThemeChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("without saved themes", () => {
+ it("shows color inputs directly without theme cards", () => {
+ setup({ savedThemes: [] });
+
+ expect(screen.getByText("Brand color")).toBeInTheDocument();
+ expect(screen.getByText("Text color")).toBeInTheDocument();
+ expect(screen.getByText("Background color")).toBeInTheDocument();
+
+ expect(screen.queryByTestId("theme-card-Custom")).not.toBeInTheDocument();
+ });
+ });
+});
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.tsx
index d6e03243b8f..c996b7e0ee2 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
@@ -9,6 +9,7 @@ import {
import { match } from "ts-pattern";
import { applyThemePreset } from "embedding-sdk-shared/lib/apply-theme-preset";
+import { useListEmbeddingThemesQuery } from "metabase/api/embedding-theme";
import { useSetting } from "metabase/common/hooks";
import { METABASE_CONFIG_IS_PROXY_FIELD_NAME } from "metabase/embedding/embedding-iframe-sdk/constants";
// we import the equivalent of embed.js so that we don't add extra loading time
@@ -22,6 +23,7 @@ import { colors as defaultMetabaseColors } from "metabase/ui/colors";
import { useSdkIframeEmbedSetupContext } from "../context";
import { getDerivedDefaultColorsForEmbedFlow } from "../utils/derived-colors-for-embed-flow";
+import { resolveSavedTheme } from "../utils/resolve-saved-theme";
import { getConfigurableThemeColors } from "../utils/theme-colors";
import { EmbedPreviewLoadingOverlay } from "./EmbedPreviewLoadingOverlay";
@@ -47,6 +49,10 @@ const SdkIframeEmbedPreviewInner = () => {
const instanceUrl = useSetting("site-url");
const applicationColors = useSetting("application-colors");
+ const { data: savedThemes } = useListEmbeddingThemesQuery(undefined, {
+ skip: !isSimpleEmbedFeatureAvailable || !settings.theme?.id,
+ });
+
const containerRef = useRef<HTMLDivElement>(null);
const defineMetabaseConfig = useCallback(
@@ -65,9 +71,14 @@ const SdkIframeEmbedPreviewInner = () => {
}
}, []);
+ const effectiveTheme = useMemo(
+ () => resolveSavedTheme({ theme: settings.theme, savedThemes }),
+ [settings.theme, savedThemes],
+ );
+
const theme = useMemo(() => {
- if (settings.theme?.preset) {
- return applyThemePreset(settings.theme);
+ if (effectiveTheme?.preset) {
+ return applyThemePreset(effectiveTheme);
}
// TODO(EMB-696): There is a bug in the SDK where if we set the theme back to undefined,
@@ -85,12 +96,12 @@ const SdkIframeEmbedPreviewInner = () => {
const derivedTheme = getDerivedDefaultColorsForEmbedFlow({
isSimpleEmbedFeatureAvailable,
- theme: settings.theme ?? defaultTheme,
+ theme: effectiveTheme ?? defaultTheme,
applicationColors: applicationColors ?? undefined,
});
return derivedTheme;
- }, [isSimpleEmbedFeatureAvailable, applicationColors, settings.theme]);
+ }, [isSimpleEmbedFeatureAvailable, applicationColors, effectiveTheme]);
const metabaseConfig = useMemo(
() => ({
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
index 408a325ddd0..eff1e3c4f0a 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
@@ -3,6 +3,7 @@ import { Link } from "react-router";
import { P, match } from "ts-pattern";
import { c, t } from "ttag";
+import { useListEmbeddingThemesQuery } from "metabase/api/embedding-theme";
import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { useDocsUrl, useHasEmailSetup } from "metabase/common/hooks";
import type {
@@ -26,8 +27,9 @@ import { UPSELL_CAMPAIGN_BEHAVIOR } from "../analytics";
import { useSdkIframeEmbedSetupContext } from "../context";
import { getBehaviorDocsUrlParams } from "../utils/get-behavior-docs-url-params";
-import { ColorCustomizationSection } from "./Appearance/ColorCustomizationSection";
+import { BaseAppearanceSection } from "./Appearance/BaseAppearanceSection";
import { SimpleThemeSwitcherSection } from "./Appearance/SimpleThemeSwitcherSection";
+import { ThemeSelectorSection } from "./Appearance/ThemeSelectorSection";
import { EmbeddingUpsell } from "./Common/EmbeddingUpsell";
import { WithNotAvailableForOssOrGuestEmbedsGuard } from "./Common/WithNotAvailableForOssOrGuestEmbedsGuard";
import { LegacyStaticEmbeddingAlert } from "./LegacyStaticEmbeddingAlert";
@@ -330,6 +332,19 @@ const AppearanceSection = () => {
const { theme } = settings;
+ const { data: savedThemes } = useListEmbeddingThemesQuery(undefined, {
+ skip: !isSimpleEmbedFeatureAvailable,
+ });
+
+ const updateThemeId = useCallback(
+ (themeId: number | undefined) => {
+ updateSettings({
+ theme: themeId ? { id: themeId } : undefined,
+ } satisfies Partial<typeof settings>);
+ },
+ [updateSettings],
+ );
+
const updateThemePreset = useCallback(
(preset: MetabaseThemePreset) => {
updateSettings({ theme: { preset } } satisfies Partial<typeof settings>);
@@ -346,6 +361,16 @@ const AppearanceSection = () => {
[theme, updateSettings],
);
+ const resetTheme = useCallback(
+ () =>
+ updateSettings({ theme: undefined } satisfies Partial<typeof settings>),
+ [updateSettings],
+ );
+
+ const hasSavedThemes = (savedThemes?.length ?? 0) > 0;
+ const showHeaderReset =
+ isSimpleEmbedFeatureAvailable && !hasSavedThemes && !!theme?.colors;
+
const appearanceSection = match(settings)
.with({ template: "exploration" }, () => null)
.with({ componentName: "metabase-metabot" }, () => <MetabotLayoutSetting />)
@@ -374,23 +399,37 @@ const AppearanceSection = () => {
return (
<Card p="md">
- {isSimpleEmbedFeatureAvailable ? (
- <ColorCustomizationSection
- theme={theme}
- onColorChange={updateColors}
- onColorReset={() =>
- updateSettings({ theme: undefined } satisfies Partial<
- typeof settings
- >)
- }
- />
- ) : (
- <SimpleThemeSwitcherSection
- preset={theme?.preset}
- onPresetChange={updateThemePreset}
- />
- )}
-
+ <BaseAppearanceSection
+ icons={
+ showHeaderReset ? (
+ <Tooltip label={t`Reset colors`}>
+ <Icon
+ name="revert"
+ size={16}
+ c="brand"
+ onClick={resetTheme}
+ aria-label={t`Reset colors`}
+ style={{ cursor: "pointer" }}
+ />
+ </Tooltip>
+ ) : null
+ }
+ >
+ {isSimpleEmbedFeatureAvailable ? (
+ <ThemeSelectorSection
+ savedThemes={savedThemes ?? []}
+ theme={theme}
+ onThemeChange={updateThemeId}
+ onColorChange={updateColors}
+ onColorReset={resetTheme}
+ />
+ ) : (
+ <SimpleThemeSwitcherSection
+ preset={theme?.preset}
+ onPresetChange={updateThemePreset}
+ />
+ )}
+ </BaseAppearanceSection>
{appearanceSection && <Divider mt="lg" mb="md" />}
{appearanceSection}
</Card>
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx
index 2d94e6d3679..f0b8bbb9c3c 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/test-setup.tsx
@@ -1,3 +1,5 @@
+import fetchMock from "fetch-mock";
+
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
findRequests,
@@ -70,6 +72,7 @@ export const setup = (options?: {
setupNotificationChannelsEndpoints(
options?.hasEmailSetup ? { email: { configured: true } as any } : {},
);
+ fetchMock.get("path:/api/embed-theme", []);
renderWithProviders(
<SdkIframeEmbedSetupModal
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts
index 13565d3a8af..ac8f3f25683 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-settings.ts
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { P, match } from "ts-pattern";
-import _ from "underscore";
import { useSetting, useUserSetting } from "metabase/common/hooks";
import { USER_SETTINGS_DEBOUNCE_MS } from "metabase/embedding/embedding-iframe-sdk-setup/constants";
@@ -25,14 +24,12 @@ const getSettingsToPersist = ({
isSimpleEmbedFeatureAvailable: boolean;
settings: Partial<SdkIframeEmbedSetupSettings>;
}): Partial<Pick<SdkIframeEmbedSetupSettings, "theme">> => {
- const keys = [];
-
- // We don't allow theme change when `simple embedding` feature is not available.
- if (isSimpleEmbedFeatureAvailable) {
- keys.push("theme");
+ // Theme customization requires the `simple embedding` feature.
+ if (!isSimpleEmbedFeatureAvailable || !settings.theme) {
+ return {};
}
- return _.pick(settings, keys);
+ return { theme: settings.theme };
};
const usePersistedSettings = ({
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts
index 3890f576664..164f1273aaa 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-sdk-iframe-embed-snippet.ts
@@ -1,10 +1,12 @@
import { useMemo } from "react";
+import { useListEmbeddingThemesQuery } from "metabase/api/embedding-theme";
import { useSetting } from "metabase/common/hooks";
import { useSdkIframeEmbedSetupContext } from "../context";
import { getDerivedDefaultColorsForEmbedFlow } from "../utils/derived-colors-for-embed-flow";
import { getEmbedSnippet } from "../utils/embed-snippet";
+import { resolveSavedTheme } from "../utils/resolve-saved-theme";
export function useSdkIframeEmbedSnippet() {
const instanceUrl = useSetting("site-url");
@@ -15,14 +17,22 @@ export function useSdkIframeEmbedSnippet() {
experience,
guestEmbedSignedTokenForSnippet,
} = useSdkIframeEmbedSetupContext();
+ const { data: savedThemes } = useListEmbeddingThemesQuery();
return useMemo(() => {
+ // Inline the saved theme's settings (and drop the wizard-only `id` field)
+ // so the snippet is self-contained and matches what embed.js expects.
+ const resolvedTheme = resolveSavedTheme({
+ theme: settings.theme,
+ savedThemes,
+ });
+
// Apply derived colors to the settings for the code snippet
const derivedTheme =
- settings.theme &&
+ resolvedTheme &&
getDerivedDefaultColorsForEmbedFlow({
isSimpleEmbedFeatureAvailable,
- theme: settings.theme,
+ theme: resolvedTheme,
applicationColors: applicationColors ?? undefined,
});
@@ -34,6 +44,7 @@ export function useSdkIframeEmbedSnippet() {
});
}, [
settings,
+ savedThemes,
applicationColors,
instanceUrl,
experience,
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts
index 20186895748..f59e60080d6 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/types.ts
@@ -7,8 +7,16 @@ import type {
SdkIframeEmbedAuthTypeSettings,
SdkIframeEmbedBaseSettings,
} from "metabase/embedding/embedding-iframe-sdk/types/embed";
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
import type { BaseRecentItem } from "metabase-types/api";
+/**
+ * Wizard-scoped theme: either an inline MetabaseTheme or a reference to a
+ * saved EmbeddingTheme via `id`. The preview resolves `id` back to an inline
+ * theme before handing it to embed.js.
+ */
+export type SdkIframeEmbedSetupTheme = MetabaseTheme & { id?: number };
+
export type SdkIframeEmbedSetupExperience =
| "dashboard"
| "chart"
@@ -56,7 +64,8 @@ export type SdkIframeEmbedSetupTemplateSettings =
*/
export type SdkIframeEmbedSetupSettings = Omit<
SdkIframeEmbedBaseSettings,
- "instanceUrl"
-> &
- Partial<SdkIframeEmbedSetupGuestEmbedSettings> &
+ "instanceUrl" | "theme"
+> & {
+ theme?: SdkIframeEmbedSetupTheme;
+} & Partial<SdkIframeEmbedSetupGuestEmbedSettings> &
SdkIframeEmbedSetupTemplateSettings;
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.ts
new file mode 100644
index 00000000000..b91ee8ced4a
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.ts
@@ -0,0 +1,44 @@
+import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import type { SdkIframeEmbedSetupTheme } from "../types";
+
+/**
+ * Resolves a wizard theme into an inline theme for the preview.
+ *
+ * If the theme references a saved theme via `id`, the saved theme's settings
+ * are merged with any inline overrides on the wizard theme — inline values
+ * (including per-color overrides) take precedence. The wizard-only `id` is
+ * stripped so the result matches the shape embed.js expects.
+ *
+ * Returns the raw input (minus `id`) when there's no id match or when saved
+ * themes haven't loaded yet.
+ */
+export function resolveSavedTheme({
+ theme,
+ savedThemes,
+}: {
+ theme: SdkIframeEmbedSetupTheme | undefined;
+ savedThemes: EmbeddingTheme[] | undefined;
+}): MetabaseTheme | undefined {
+ if (!theme) {
+ return undefined;
+ }
+
+ const { id, ...themeWithoutId } = theme;
+
+ if (!id) {
+ return themeWithoutId;
+ }
+
+ const saved = savedThemes?.find((t) => t.id === id);
+ if (!saved) {
+ return themeWithoutId;
+ }
+
+ return {
+ ...saved.settings,
+ ...themeWithoutId,
+ colors: { ...saved.settings.colors, ...theme.colors },
+ };
+}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.unit.spec.ts
new file mode 100644
index 00000000000..b36ae2ed239
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/resolve-saved-theme.unit.spec.ts
@@ -0,0 +1,123 @@
+import type { EmbeddingTheme } from "metabase-types/api/embedding-theme";
+
+import type { SdkIframeEmbedSetupTheme } from "../types";
+
+import { resolveSavedTheme } from "./resolve-saved-theme";
+
+const SAVED_THEMES: EmbeddingTheme[] = [
+ {
+ id: 1,
+ name: "Dark",
+ settings: {
+ colors: {
+ brand: "#BB86FC",
+ "text-primary": "#FFFFFF",
+ background: "#121212",
+ },
+ fontFamily: "Inter",
+ },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ },
+ {
+ id: 2,
+ name: "Ocean",
+ settings: {
+ colors: { brand: "#0077B6" },
+ },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ },
+];
+
+describe("resolveSavedTheme", () => {
+ it("returns undefined when no theme is set", () => {
+ expect(
+ resolveSavedTheme({ theme: undefined, savedThemes: SAVED_THEMES }),
+ ).toBeUndefined();
+ });
+
+ it("returns the raw theme when there is no id", () => {
+ const theme: SdkIframeEmbedSetupTheme = { colors: { brand: "#FF0000" } };
+
+ expect(
+ resolveSavedTheme({ theme, savedThemes: SAVED_THEMES }),
+ ).toStrictEqual(theme);
+ });
+
+ it("strips the id when it does not match any saved theme", () => {
+ const theme: SdkIframeEmbedSetupTheme = { id: 999 };
+
+ expect(
+ resolveSavedTheme({ theme, savedThemes: SAVED_THEMES }),
+ ).toStrictEqual({});
+ });
+
+ it("strips the id when savedThemes is still loading", () => {
+ const theme: SdkIframeEmbedSetupTheme = { id: 1 };
+
+ expect(resolveSavedTheme({ theme, savedThemes: undefined })).toStrictEqual(
+ {},
+ );
+ });
+
+ it("resolves the saved theme when only an id is set", () => {
+ const resolved = resolveSavedTheme({
+ theme: { id: 1 },
+ savedThemes: SAVED_THEMES,
+ });
+
+ expect(resolved).toStrictEqual({
+ colors: {
+ brand: "#BB86FC",
+ "text-primary": "#FFFFFF",
+ background: "#121212",
+ },
+ fontFamily: "Inter",
+ });
+ });
+
+ it("merges inline colors on top of the saved theme, with inline values winning", () => {
+ const resolved = resolveSavedTheme({
+ theme: { id: 1, colors: { brand: "#FF0000" } },
+ savedThemes: SAVED_THEMES,
+ });
+
+ expect(resolved?.colors).toStrictEqual({
+ brand: "#FF0000",
+ "text-primary": "#FFFFFF",
+ background: "#121212",
+ });
+ });
+
+ it("lets inline top-level overrides (e.g. fontFamily) win over the saved theme", () => {
+ const resolved = resolveSavedTheme({
+ theme: { id: 1, fontFamily: "Roboto" },
+ savedThemes: SAVED_THEMES,
+ });
+
+ expect(resolved?.fontFamily).toBe("Roboto");
+ });
+
+ it("handles saved themes without a colors map", () => {
+ const saved: EmbeddingTheme[] = [
+ {
+ id: 3,
+ name: "Bare",
+ settings: { fontFamily: "Lato" },
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ },
+ ];
+
+ const resolved = resolveSavedTheme({
+ theme: { id: 3, colors: { brand: "#00FF00" } },
+ savedThemes: saved,
+ });
+
+ expect(resolved).toStrictEqual({
+ fontFamily: "Lato",
+ colors: { brand: "#00FF00" },
+ });
+ });
+});
diff --git a/frontend/src/metabase/transforms/pages/TransformInspectorUpsellPage/TransformInspectorUpsellPage.tsx b/frontend/src/metabase/transforms/pages/TransformInspectorUpsellPage/TransformInspectorUpsellPage.tsx
index c6f9d0d4019..3d72522ec0b 100644
--- a/frontend/src/metabase/transforms/pages/TransformInspectorUpsellPage/TransformInspectorUpsellPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformInspectorUpsellPage/TransformInspectorUpsellPage.tsx
@@ -1,12 +1,12 @@
import { t } from "ttag";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { DottedBackground } from "metabase/common/components/upsells/components/DottedBackground";
+import { LineDecorator } from "metabase/common/components/upsells/components/LineDecorator";
import { useUpgradeAction } from "metabase/common/components/upsells/components/UpgradeModal";
+import { UpsellCardContent } from "metabase/common/components/upsells/components/UpsellCardContent";
import { DATA_STUDIO_UPGRADE_URL } from "metabase/common/components/upsells/constants";
import { PageContainer } from "metabase/data-studio/common/components/PageContainer";
-import { DottedBackground } from "metabase/data-studio/upsells/components/DottedBackground";
-import { LineDecorator } from "metabase/data-studio/upsells/components/LineDecorator";
-import { UpsellCardContent } from "metabase/data-studio/upsells/components/UpsellCardContent";
import { TransformHeader } from "metabase/transforms/components/TransformHeader";
import {
INSPECTOR_UPSELL_CAMPAIGN,
diff --git a/resources/frontend_client/app/assets/img/upsell-themes.png b/resources/frontend_client/app/assets/img/upsell-themes.png
new file mode 100644
index 00000000000..061adf68eb4
Binary files /dev/null and b/resources/frontend_client/app/assets/img/upsell-themes.png differ
diff --git a/resources/migrations/059_update_migrations.yaml b/resources/migrations/059_update_migrations.yaml
index 18f88acf6bc..5398e953eb7 100644
--- a/resources/migrations/059_update_migrations.yaml
+++ b/resources/migrations/059_update_migrations.yaml
@@ -3482,6 +3482,57 @@ databaseChangeLog:
- customChange:
class: "metabase.app_db.custom_migrations.DropMedallionNamesForDataLayer"
+ - changeSet:
+ id: v59.2026-04-08T12:00:00
+ author: heypoom
+ comment: Add embedding_theme table for embedding theme editor
+ changes:
+ - createTable:
+ tableName: embedding_theme
+ remarks: Stores themes created via the embedding theme editor
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ remarks: Unique ID
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: entity_id
+ type: char(21)
+ remarks: Random NanoID tag for unique identity
+ constraints:
+ nullable: true
+ unique: true
+ - column:
+ name: name
+ type: varchar(255)
+ remarks: Name of the embed theme
+ constraints:
+ nullable: false
+ - column:
+ name: settings
+ type: ${text.type}
+ remarks: JSON object of theme settings
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the theme was created
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the theme was last updated
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.clj
index f8b171fea98..8a4e86f699a 100644
--- a/src/metabase/api_routes/routes.clj
+++ b/src/metabase/api_routes/routes.clj
@@ -179,6 +179,7 @@
"/eid-translation" (+auth 'metabase.eid-translation.api)
"/email" metabase.channel.api/email-routes
"/embed" (+message-only-exceptions metabase.embedding-rest.api/embedding-routes)
+ "/embed-theme" (+auth metabase.embedding-rest.api/theme-routes)
"/field" (+auth metabase.warehouse-schema-rest.api/field-routes)
"/frontend-errors" metabase.frontend-errors.api/routes
"/geojson" 'metabase.geojson.api
diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.clj
index 947d0122d2b..5f7ba8bd74a 100644
--- a/src/metabase/cmd/copy.clj
+++ b/src/metabase/cmd/copy.clj
@@ -59,6 +59,7 @@
:model/Database
:model/User
:model/Setting
+ :model/EmbeddingTheme
:model/Table
:model/Field
:model/FieldValues
diff --git a/src/metabase/embedding/models/theme.clj b/src/metabase/embedding/models/theme.clj
new file mode 100644
index 00000000000..03b089d1a16
--- /dev/null
+++ b/src/metabase/embedding/models/theme.clj
@@ -0,0 +1,38 @@
+(ns metabase.embedding.models.theme
+ "Model for embedding themes for use in the embedding theme editor."
+ (:require
+ [metabase.models.interface :as mi]
+ [metabase.models.serialization :as serdes]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/EmbeddingTheme [_model] :embedding_theme)
+
+(doto :model/EmbeddingTheme
+ (derive :metabase/model)
+ (derive ::mi/write-policy.superuser)
+ (derive ::mi/read-policy.superuser)
+ (derive :hook/entity-id)
+ (derive :hook/timestamped?))
+
+;;;; transforms
+
+(t2/deftransforms :model/EmbeddingTheme
+ {:settings mi/transform-json})
+
+;;;; serialization
+
+(defmethod serdes/hash-fields :model/EmbeddingTheme
+ [_embedding-theme]
+ [:name :created_at])
+
+(defmethod serdes/make-spec "EmbeddingTheme"
+ [_model-name _opts]
+ {:copy [:entity_id :name :settings]
+ :skip []
+ :transform {:created_at (serdes/date)
+ :updated_at (serdes/date)}})
+
+(defmethod serdes/storage-path "EmbeddingTheme"
+ [entity _ctx]
+ [{:label "embedding_themes"} {:label (:name entity) :key (:entity_id entity)}])
diff --git a/src/metabase/embedding/settings.clj b/src/metabase/embedding/settings.clj
index ae8981a380f..f95e8b2fe8c 100644
--- a/src/metabase/embedding/settings.clj
+++ b/src/metabase/embedding/settings.clj
@@ -319,3 +319,12 @@
:visibility :admin
:can-read-from-env? false
:doc false)
+
+(defsetting default-embedding-themes-seeded
+ (deferred-tru "Whether the default Light and Dark embedding themes have been seeded into the database.")
+ :type :boolean
+ :default false
+ :visibility :admin
+ :export? false
+ :can-read-from-env? false
+ :doc false)
diff --git a/src/metabase/embedding_rest/api.clj b/src/metabase/embedding_rest/api.clj
index 841ab553a49..2f23a572b3f 100644
--- a/src/metabase/embedding_rest/api.clj
+++ b/src/metabase/embedding_rest/api.clj
@@ -1,11 +1,14 @@
(ns metabase.embedding-rest.api
(:require
+ [metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.embedding-rest.api.embed]
- [metabase.embedding-rest.api.preview-embed]))
+ [metabase.embedding-rest.api.preview-embed]
+ [metabase.embedding-rest.api.theme]))
(comment metabase.embedding-rest.api.embed/keep-me
- metabase.embedding-rest.api.preview-embed/keep-me)
+ metabase.embedding-rest.api.preview-embed/keep-me
+ metabase.embedding-rest.api.theme/keep-me)
(def ^{:arglists '([request respond raise])} embedding-routes
"`/api/embed` routes"
@@ -14,3 +17,7 @@
(def ^{:arglists '([request respond raise])} preview-embedding-routes
"`/api/preview_embed` routes"
(api.macros/ns-handler 'metabase.embedding-rest.api.preview-embed))
+
+(def ^{:arglists '([request respond raise])} theme-routes
+ "`/api/embed-theme` routes"
+ (api.macros/ns-handler 'metabase.embedding-rest.api.theme api/+check-superuser))
diff --git a/src/metabase/embedding_rest/api/theme.clj b/src/metabase/embedding_rest/api/theme.clj
new file mode 100644
index 00000000000..8f29e0e7685
--- /dev/null
+++ b/src/metabase/embedding_rest/api/theme.clj
@@ -0,0 +1,97 @@
+(ns metabase.embedding-rest.api.theme
+ "Endpoints for managing embedding themes."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.embedding.settings :as embedding.settings]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defonce ^:private seed-defaults-lock (Object.))
+
+(mr/def ::EmbeddingTheme
+ [:map
+ [:id ms/PositiveInt]
+ [:entity_id ms/NonBlankString]
+ [:name ms/NonBlankString]
+ [:settings :map]
+ [:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]
+ [:updated_at (ms/InstanceOfClass java.time.temporal.Temporal)]])
+
+(api.macros/defendpoint :get "/" :- [:sequential ::EmbeddingTheme]
+ "Fetch a list of all embedding themes."
+ []
+ ; settings field is used for theme card previews.
+ ; we can optimize this by only selecting the preview colors needed.
+ (t2/select :model/EmbeddingTheme {:order-by [[:created_at :asc]]
+ :select [:id :entity_id :name :settings :created_at :updated_at]}))
+
+(api.macros/defendpoint :get "/:id" :- ::EmbeddingTheme
+ "Fetch a single embedding theme by ID."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]
+ (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))
+ (t2/select-one :model/EmbeddingTheme :id id))
+
+(api.macros/defendpoint :post "/" :- ::EmbeddingTheme
+ "Create a new embedding theme."
+ [_route-params
+ _query-params
+ {:keys [name settings]} :- [:map
+ [:name ms/NonBlankString]
+ [:settings :map]]]
+ (t2/insert-returning-instance! :model/EmbeddingTheme
+ {:name name
+ :settings settings}))
+
+(api.macros/defendpoint :put "/:id" :- ::EmbeddingTheme
+ "Update an embedding theme."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ _query-params
+ {:keys [name settings]} :- [:map
+ [:name {:optional true} [:maybe ms/NonBlankString]]
+ [:settings {:optional true} [:maybe :map]]]]
+ (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))
+ (t2/update! :model/EmbeddingTheme id
+ (cond-> {}
+ name (assoc :name name)
+ settings (assoc :settings settings)))
+ (t2/select-one :model/EmbeddingTheme :id id))
+
+(api.macros/defendpoint :delete "/:id" :- :nil
+ "Delete an embedding theme."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]
+ (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))
+ (t2/delete! :model/EmbeddingTheme :id id)
+ nil)
+
+(api.macros/defendpoint :post "/:id/copy" :- ::EmbeddingTheme
+ "Copy an embedding theme."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]
+ (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))
+ (let [source-theme (t2/select-one :model/EmbeddingTheme :id id)]
+ (t2/insert-returning-instance! :model/EmbeddingTheme
+ {:name (tru "Copy of {0}" (:name source-theme))
+ :settings (:settings source-theme)})))
+
+(api.macros/defendpoint :post "/seed-defaults" :- :nil
+ "Seed default embedding themes on first call, using the payloads built by the frontend from the
+ `METABASE_LIGHT_THEME` / `METABASE_DARK_THEME` constants.
+
+ Idempotent: guarded by the `default-embedding-themes-seeded` setting. Once flipped, subsequent calls
+ are no-ops even if the admin has since deleted the seeded themes, so deletions are preserved."
+ [_route-params
+ _query-params
+ {:keys [themes]} :- [:map
+ [:themes [:sequential [:map
+ [:name ms/NonBlankString]
+ [:settings :map]]]]]]
+ (locking seed-defaults-lock
+ (t2/with-transaction [_conn]
+ (when-not (embedding.settings/default-embedding-themes-seeded)
+ (t2/insert! :model/EmbeddingTheme themes)
+ (embedding.settings/default-embedding-themes-seeded! true))))
+ nil)
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 9d710379f51..9ccf106ba5c 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -46,6 +46,7 @@
:model/Dimension metabase.warehouse-schema.models.dimension
:model/Document metabase.documents.models.document
:model/DocumentBookmark metabase.bookmarks.models.bookmark
+ :model/EmbeddingTheme metabase.embedding.models.theme
:model/Field metabase.warehouse-schema.models.field
:model/FieldUserSettings metabase.warehouse-schema.models.field-user-settings
:model/FieldValues metabase.warehouse-schema.models.field-values
diff --git a/test/metabase/embedding_rest/api/theme_test.clj b/test/metabase/embedding_rest/api/theme_test.clj
new file mode 100644
index 00000000000..e98f81b5d4f
--- /dev/null
+++ b/test/metabase/embedding_rest/api/theme_test.clj
@@ -0,0 +1,211 @@
+(ns metabase.embedding-rest.api.theme-test
+ "Tests for /api/embed-theme endpoints."
+ (:require
+ [clojure.test :refer :all]
+ [metabase.embedding.settings :as embedding.settings]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :db :test-users :web-server))
+
+(deftest create-theme-test
+ (testing "POST /api/embed-theme"
+ (testing "creates a new embedding theme"
+ (mt/with-empty-h2-app-db!
+ (let [theme-name "My Test Theme"
+ settings {:color {:brand "#FF0000"}}
+ response (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name theme-name
+ :settings settings})]
+ (is (= #{:id :entity_id :name :settings :created_at :updated_at}
+ (set (keys response))))
+ (is (= theme-name (:name response)))
+ (is (= settings (:settings response)))
+ (is (pos-int? (:id response)))
+ (is (some? (:created_at response)))
+ (is (some? (:updated_at response))))))
+ (testing "requires superuser permissions"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "embed-theme"
+ {:name "Test Theme"
+ :settings {}}))))
+ (testing "requires a non-blank name"
+ (is (=? {:errors {:name "value must be a non-blank string."}}
+ (mt/user-http-request :crowberto :post 400 "embed-theme"
+ {:name ""
+ :settings {}}))))
+ (testing "requires settings to be a map"
+ (is (=? {:errors {:settings string?}}
+ (mt/user-http-request :crowberto :post 400 "embed-theme"
+ {:name "Test Theme"
+ :settings "not a map"}))))))
+
+(deftest list-themes-test
+ (testing "GET /api/embed-theme"
+ (testing "returns a list of all themes"
+ (mt/with-empty-h2-app-db!
+ (is (= [] (mt/user-http-request :crowberto :get 200 "embed-theme")))
+ (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Theme 1"
+ :settings {:color {:brand "#FF0000"}}})
+ (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Theme 2"
+ :settings {:color {:brand "#00FF00"}}})
+ (let [themes (mt/user-http-request :crowberto :get 200 "embed-theme")]
+ (is (= 2 (count themes)))
+ ; settings is used for theme card previews
+ (is (= #{:id :entity_id :name :settings :created_at :updated_at}
+ (set (keys (first themes)))))
+ (testing "themes are ordered by oldest first"
+ (is (= ["Theme 1" "Theme 2"]
+ (map :name themes)))))))
+ (testing "requires superuser permissions"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "embed-theme"))))))
+
+(deftest get-theme-test
+ (testing "GET /api/embed-theme/:id"
+ (testing "returns a single theme with full details"
+ (mt/with-empty-h2-app-db!
+ (let [settings {:color {:brand "#FF0000"}}
+ created (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Test Theme"
+ :settings settings})
+ theme-id (:id created)
+ response (mt/user-http-request :crowberto :get 200 (format "embed-theme/%s" theme-id))]
+ (is (= #{:id :entity_id :name :settings :created_at :updated_at}
+ (set (keys response))))
+ (is (= "Test Theme" (:name response)))
+ (is (= settings (:settings response))))))
+ (testing "returns 404 for non-existent theme"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :get 404 "embed-theme/999999"))))
+ (testing "requires superuser permissions"
+ (mt/with-temp [:model/EmbeddingTheme {theme-id :id} {:name "Test Theme"
+ :settings {}}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 (format "embed-theme/%s" theme-id))))))))
+
+(deftest update-theme-test
+ (testing "PUT /api/embed-theme/:id"
+ (testing "updates theme name"
+ (mt/with-empty-h2-app-db!
+ (let [created (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Original Name"
+ :settings {:color {:brand "#FF0000"}}})
+ theme-id (:id created)
+ response (mt/user-http-request :crowberto :put 200 (format "embed-theme/%s" theme-id)
+ {:name "Updated Name"})]
+ (is (= "Updated Name" (:name response)))
+ (is (= {:color {:brand "#FF0000"}} (:settings response))))))
+ (testing "updates theme settings"
+ (mt/with-empty-h2-app-db!
+ (let [created (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Test Theme"
+ :settings {:color {:brand "#FF0000"}}})
+ theme-id (:id created)
+ response (mt/user-http-request :crowberto :put 200 (format "embed-theme/%s" theme-id)
+ {:settings {:color {:brand "#00FF00"}}})]
+ (is (= "Test Theme" (:name response)))
+ (is (= {:color {:brand "#00FF00"}} (:settings response))))))
+ (testing "returns 404 for non-existent theme"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :put 404 "embed-theme/999999"
+ {:name "Updated Name"}))))
+ (testing "requires superuser permissions"
+ (mt/with-temp [:model/EmbeddingTheme {theme-id :id} {:name "Test Theme"
+ :settings {}}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "embed-theme/%s" theme-id)
+ {:name "Updated Name"})))))))
+
+(deftest delete-theme-test
+ (testing "DELETE /api/embed-theme/:id"
+ (testing "deletes a theme"
+ (mt/with-empty-h2-app-db!
+ (let [created (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name "Test Theme"
+ :settings {}})
+ theme-id (:id created)]
+ (is (t2/exists? :model/EmbeddingTheme :id theme-id))
+ (is (nil? (mt/user-http-request :crowberto :delete 204 (format "embed-theme/%s" theme-id))))
+ (is (not (t2/exists? :model/EmbeddingTheme :id theme-id))))))
+ (testing "returns 404 for non-existent theme"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :delete 404 "embed-theme/999999"))))
+ (testing "requires superuser permissions"
+ (mt/with-temp [:model/EmbeddingTheme {theme-id :id} {:name "Test Theme"
+ :settings {}}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 (format "embed-theme/%s" theme-id))))
+ (is (t2/exists? :model/EmbeddingTheme :id theme-id))))))
+
+(deftest copy-theme-test
+ (testing "POST /api/embed-theme/:id/copy"
+ (testing "duplicates a theme with 'Copy of' prefix"
+ (mt/with-empty-h2-app-db!
+ (let [original-name "My Theme"
+ original-settings {:colors {:brand "#FF0000"
+ :text-primary "#000000"}}
+ created (mt/user-http-request :crowberto :post 200 "embed-theme"
+ {:name original-name
+ :settings original-settings})
+ theme-id (:id created)
+ response (mt/user-http-request :crowberto :post 200 (format "embed-theme/%s/copy" theme-id))]
+ (is (= #{:id :entity_id :name :settings :created_at :updated_at}
+ (set (keys response))))
+ (is (= "Copy of My Theme" (:name response)))
+ (is (= original-settings (:settings response)))
+ (is (not= theme-id (:id response)))
+ (testing "both themes exist in the database"
+ (is (t2/exists? :model/EmbeddingTheme :id theme-id))
+ (is (t2/exists? :model/EmbeddingTheme :id (:id response)))))))
+ (testing "returns 404 for non-existent theme"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :post 404 "embed-theme/999999/copy"))))
+ (testing "requires superuser permissions"
+ (mt/with-temp [:model/EmbeddingTheme {theme-id :id} {:name "Test Theme"
+ :settings {}}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 (format "embed-theme/%s/copy" theme-id))))))))
+
+(def ^:private example-seed-body
+ {:themes [{:name "Light"
+ :settings {:colors {:brand "#509EE3"}}}
+ {:name "Dark"
+ :settings {:colors {:brand "#88BF4D"}}}]})
+
+(deftest seed-defaults-theme-test
+ (testing "POST /api/embed-theme/seed-defaults"
+ (testing "seeds the provided themes and flips the setting on first call"
+ (mt/with-empty-h2-app-db!
+ (is (false? (embedding.settings/default-embedding-themes-seeded)))
+ (is (nil? (mt/user-http-request :crowberto :post 204 "embed-theme/seed-defaults" example-seed-body)))
+ (is (= ["Light" "Dark"]
+ (map :name (t2/select :model/EmbeddingTheme {:order-by [[:created_at :asc]]}))))
+ (is (true? (embedding.settings/default-embedding-themes-seeded)))))
+ (testing "subsequent calls are a no-op once the setting is flipped — even if themes were deleted"
+ (mt/with-empty-h2-app-db!
+ (mt/user-http-request :crowberto :post 204 "embed-theme/seed-defaults" example-seed-body)
+ (t2/delete! :model/EmbeddingTheme)
+ (mt/user-http-request :crowberto :post 204 "embed-theme/seed-defaults" example-seed-body)
+ (is (zero? (t2/count :model/EmbeddingTheme))
+ "Admin deletion should be preserved — no re-seed")))
+ (testing "rolls back atomically when an insert fails"
+ (mt/with-empty-h2-app-db!
+ (let [original-insert t2/insert!]
+ (with-redefs [t2/insert! (fn [model & rows]
+ (if (= model :model/EmbeddingTheme)
+ (throw (ex-info "boom" {}))
+ (apply original-insert model rows)))]
+ (mt/user-http-request :crowberto :post 500 "embed-theme/seed-defaults" example-seed-body)))
+ (is (zero? (t2/count :model/EmbeddingTheme)))
+ (is (false? (embedding.settings/default-embedding-themes-seeded))
+ "Setting flag must not flip when the insert fails")))
+ (testing "requires superuser permissions"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "embed-theme/seed-defaults" example-seed-body))))
+ (testing "requires a themes array of non-blank names and map settings"
+ (is (=? {:errors {:themes string?}}
+ (mt/user-http-request :crowberto :post 400 "embed-theme/seed-defaults" {:themes "nope"}))))))
diff --git a/test_resources/serialization_baseline/embedding_themes/dark.yaml b/test_resources/serialization_baseline/embedding_themes/dark.yaml
new file mode 100644
index 00000000000..4e186fca345
--- /dev/null
+++ b/test_resources/serialization_baseline/embedding_themes/dark.yaml
@@ -0,0 +1,9 @@
+created_at: '2025-11-05T17:34:01.946143Z'
+entity_id: cAGrIWAv42Lh6i9Jcpu0J
+name: Dark
+settings: {}
+updated_at: '2025-11-05T17:34:01.946143Z'
+serdes/meta:
+- id: cAGrIWAv42Lh6i9Jcpu0J
+ label: dark
+ model: EmbeddingTheme
diff --git a/test_resources/serialization_baseline/embedding_themes/light.yaml b/test_resources/serialization_baseline/embedding_themes/light.yaml
new file mode 100644
index 00000000000..a069ff2be4d
--- /dev/null
+++ b/test_resources/serialization_baseline/embedding_themes/light.yaml
@@ -0,0 +1,9 @@
+created_at: '2025-11-05T17:34:01.946143Z'
+entity_id: WvRp2yy6Tk98WunjkA8aE
+name: Light
+settings: {}
+updated_at: '2025-11-05T17:34:01.946143Z'
+serdes/meta:
+- id: WvRp2yy6Tk98WunjkA8aE
+ label: light
+ model: EmbeddingTheme