Skip to content

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

fix(sdk): Scope Mantine styles to SDK (#62103)

Timofey Kachalovf3ef92f7ca88
diff --git a/e2e/support/helpers/embedding-sdk-helpers/host-app-styles.css b/e2e/support/helpers/embedding-sdk-helpers/host-app-styles.css
new file mode 100644
index 00000000000..bcd624d356e
--- /dev/null
+++ b/e2e/support/helpers/embedding-sdk-helpers/host-app-styles.css
@@ -0,0 +1,7 @@
+button {
+ background: red;
+}
+
+.some-title {
+ font-size: 40px;
+}
diff --git a/e2e/test-component/scenarios/embedding-sdk/mantine-styles-tests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/mantine-styles-tests.cy.spec.tsx
new file mode 100644
index 00000000000..88dc1a9e167
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/mantine-styles-tests.cy.spec.tsx
@@ -0,0 +1,140 @@
+// To apply cypress-level mantine styles
+import "@mantine/core/styles.css";
+import "@mantine/dates/styles.css";
+
+// Mimics behavior when an app adds its own styles
+// We need to do it before importing the SDK
+import "e2e/support/helpers/embedding-sdk-helpers/host-app-styles.css";
+
+import { Button, MantineProvider, Title } from "@mantine/core";
+import {
+ InteractiveQuestion,
+ MetabaseProvider,
+} from "@metabase/embedding-sdk-react";
+
+import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { DEFAULT_SDK_AUTH_PROVIDER_CONFIG } from "e2e/support/helpers/embedding-sdk-component-testing";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+
+describe("scenarios > embedding-sdk > mantine styles leakage", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ cy.signOut();
+
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ it("css variables should not leak outside of mb-wrapper", () => {
+ cy.mount(
+ <MantineProvider
+ theme={{ colors: { brand: colorTuple("rgb(255, 0, 255)") } }}
+ >
+ <Button color="brand">outside sdk provider</Button>
+
+ <MetabaseProvider
+ authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}
+ theme={{ colors: { brand: "rgb(255, 0, 0)" } }}
+ >
+ <Button color="brand">outside sdk wrapper</Button>
+
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} isSaveEnabled />
+ </MetabaseProvider>
+ </MantineProvider>,
+ );
+
+ cy.log(
+ "Customer's elements outside of the SDK provider should have their brand color intact",
+ );
+
+ cy.contains("button", "outside sdk provider").should(
+ "have.css",
+ "background-color",
+ "rgb(255, 0, 255)",
+ );
+
+ cy.log(
+ "Customer's elements outside of the SDK components should have their brand color intact",
+ );
+
+ cy.contains("button", "outside sdk wrapper").should(
+ "have.css",
+ "background-color",
+ "rgb(255, 0, 255)",
+ );
+
+ cy.log("SDK elements should have the brand color from the Metabase theme");
+
+ getSdkRoot().within(() => {
+ cy.get("button")
+ .contains("Filter")
+ .should("have.css", "color", "rgb(255, 0, 0)");
+
+ cy.findByTestId("notebook-button").click();
+
+ cy.findByRole("button", { name: "Visualize" }).should(
+ "have.css",
+ "background-color",
+ "rgb(255, 0, 0)",
+ );
+ });
+ });
+
+ it("Mantine styles added by SDK should not override custom styles of an app", () => {
+ const TitleWrapper = () => (
+ <Title data-testid="title" className="some-title">
+ Some title
+ </Title>
+ );
+
+ cy.mount(
+ <MantineProvider>
+ <TitleWrapper />
+
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>
+ </MantineProvider>,
+ );
+
+ getSdkRoot().findByText("Product ID").should("exist");
+
+ cy.findByTestId("title").should("have.css", "font-size", "40px");
+ });
+
+ it("App styles should not affect SDK styles", () => {
+ cy.mount(
+ <MantineProvider>
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
+ </MetabaseProvider>
+ </MantineProvider>,
+ );
+
+ getSdkRoot().findByText("Product ID").should("exist");
+
+ cy.findByTestId("interactive-question-result-toolbar").within(() => {
+ cy.findByText("Filter").should(
+ "have.css",
+ "background-color",
+ "rgba(0, 0, 0, 0)",
+ );
+ });
+ });
+});
+
+export const colorTuple = (value: string) =>
+ [
+ value,
+ value,
+ value,
+ value,
+ value,
+ value,
+ value,
+ value,
+ value,
+ value,
+ ] as const;
diff --git a/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx
index 88d126ad5b4..b35b89345a0 100644
--- a/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/styles-tests.cy.spec.tsx
@@ -1,4 +1,3 @@
-import { Button, MantineProvider, Title } from "@mantine/core";
import {
CreateDashboardModal,
EditableDashboard,
@@ -8,7 +7,6 @@ import {
StaticQuestion,
defineMetabaseTheme,
} from "@metabase/embedding-sdk-react";
-import { useEffect } from "react";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
@@ -599,108 +597,6 @@ describe("scenarios > embedding-sdk > styles", () => {
expectElementToHaveNoAppliedCssRules(tag);
}
});
-
- it("css variables should not leak outside of mb-wrapper", () => {
- cy.mount(
- <MantineProvider
- theme={{ colors: { brand: colorTuple("rgb(255, 0, 255)") } }}
- >
- <Button color="brand">outside sdk provider</Button>
-
- <MetabaseProvider
- authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}
- theme={{ colors: { brand: "rgb(255, 0, 0)" } }}
- >
- <Button color="brand">outside sdk wrapper</Button>
-
- <InteractiveQuestion
- questionId={ORDERS_QUESTION_ID}
- isSaveEnabled
- />
- </MetabaseProvider>
- </MantineProvider>,
- );
-
- cy.log(
- "Customer's elements outside of the SDK provider should have their brand color intact",
- );
-
- cy.contains("button", "outside sdk provider").should(
- "have.css",
- "background-color",
- "rgb(255, 0, 255)",
- );
-
- cy.log(
- "Customer's elements outside of the SDK components should have their brand color intact",
- );
-
- cy.contains("button", "outside sdk wrapper").should(
- "have.css",
- "background-color",
- "rgb(255, 0, 255)",
- );
-
- cy.log(
- "SDK elements should have the brand color from the Metabase theme",
- );
-
- getSdkRoot().within(() => {
- cy.get("button")
- .contains("Filter")
- .should("have.css", "color", "rgb(255, 0, 0)");
-
- cy.findByTestId("notebook-button").click();
-
- cy.findByRole("button", { name: "Visualize" }).should(
- "have.css",
- "background-color",
- "rgb(255, 0, 0)",
- );
- });
- });
- });
-
- describe("styles specificity", () => {
- it("Mantine styles should have proper specificity and not override custom styles", () => {
- const TitleWrapper = () => {
- useEffect(() => {
- const style = document.createElement("style");
-
- style.innerHTML = `
- .some-title {
- font-size: 40px;
- }
- `;
-
- document.head.prepend(style);
-
- return () => {
- style.remove();
- };
- }, []);
-
- return (
- <Title data-testid="title" className="some-title">
- Some title
- </Title>
- );
- };
-
- cy.mount(
- <MantineProvider>
- <TitleWrapper />
-
- <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
- <InteractiveQuestion questionId={ORDERS_QUESTION_ID} />
- </MetabaseProvider>
- </MantineProvider>,
- );
-
- getSdkRoot().findByText("Product ID").should("exist");
-
- cy.findByTestId("title").should("have.css", "font-size", "40px");
- });
});
});
@@ -737,17 +633,3 @@ function wrapBrowserDefaultFont() {
cy.wrap(fontFamily).as("defaultBrowserFontFamily");
});
}
-
-export const colorTuple = (value: string) =>
- [
- value,
- value,
- value,
- value,
- value,
- value,
- value,
- value,
- value,
- value,
- ] as const;
diff --git a/enterprise/frontend/src/embedding-sdk/bundle.ts b/enterprise/frontend/src/embedding-sdk/bundle.ts
index 67d12476039..3aee72bf270 100644
--- a/enterprise/frontend/src/embedding-sdk/bundle.ts
+++ b/enterprise/frontend/src/embedding-sdk/bundle.ts
@@ -4,9 +4,11 @@ import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
// This applies to SDK derivatives such as new iframe embedding.
EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
-import "metabase/embedding-sdk/css/layer.module.css";
-import "metabase/embedding-sdk/css/vendor.module.css";
-import "metabase/embedding-sdk/css/index.module.css";
+import "@mantine/core/styles.css";
+import "@mantine/dates/styles.css";
+
+import "metabase/css/vendor.css";
+import "metabase/css/index.module.css";
import "metabase/lib/dayjs";
diff --git a/enterprise/frontend/src/embedding-sdk/components/private/PublicComponentStylesWrapper.tsx b/enterprise/frontend/src/embedding-sdk/components/private/PublicComponentStylesWrapper.tsx
index d8d46600c94..16b0f0b8707 100644
--- a/enterprise/frontend/src/embedding-sdk/components/private/PublicComponentStylesWrapper.tsx
+++ b/enterprise/frontend/src/embedding-sdk/components/private/PublicComponentStylesWrapper.tsx
@@ -3,7 +3,6 @@ import styled from "@emotion/styled";
import type React from "react";
import { forwardRef } from "react";
-import { isTest } from "metabase/env";
import { saveDomImageStyles } from "metabase/visualizations/lib/image-exports";
/**
@@ -63,7 +62,7 @@ export const PublicComponentStylesWrapper = forwardRef<
* - -> our other code with specificity (0,1,0) will override this as they're loaded after
*/
// note: if we move this to css.module, remember to add :global to .mb-wrapper
-const BASE_SCOPED_CSS_RESET = css`
+export const SCOPED_CSS_RESET = css`
:where(.mb-wrapper) *:where(button) {
border: 0;
background-color: transparent;
@@ -79,16 +78,3 @@ const BASE_SCOPED_CSS_RESET = css`
display: inline;
}
`;
-
-// For test env we don't use layers, because the current version of jsdom does not support it,
-// and upgrading it introduces other issues in tests.
-
-export const SCOPED_CSS_RESET = isTest
- ? BASE_SCOPED_CSS_RESET
- : css`
- @layer embedding-sdk {
- @layer reset {
- ${BASE_SCOPED_CSS_RESET}
- }
- }
- `;
diff --git a/frontend/src/metabase/embedding-sdk/css/index.module.css b/frontend/src/metabase/embedding-sdk/css/index.module.css
deleted file mode 100644
index a33817c3084..00000000000
--- a/frontend/src/metabase/embedding-sdk/css/index.module.css
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Layers are defined in the `layer.module.css`
- */
-@import "../../css/reset.module.css" layer(embedding-sdk.reset);
-@import "../../css/components/form.module.css" layer(embedding-sdk.main);
-@import "../../css/components/list.module.css" layer(embedding-sdk.main);
-@import "../../css/components/modal.module.css" layer(embedding-sdk.main);
-@import "../../css/components/tippy.module.css" layer(embedding-sdk.main);
-@import "../../css/components/grabber.module.css" layer(embedding-sdk.main);
-@import "../../css/admin.module.css" layer(embedding-sdk.main);
-@import "../../css/dashboard.module.css" layer(embedding-sdk.main);
-@import "../../css/query_builder.module.css" layer(embedding-sdk.main);
-@import "../../css/core/animation.module.css" layer(embedding-sdk.main);
diff --git a/frontend/src/metabase/embedding-sdk/css/layer.module.css b/frontend/src/metabase/embedding-sdk/css/layer.module.css
deleted file mode 100644
index 57efb5b6ef8..00000000000
--- a/frontend/src/metabase/embedding-sdk/css/layer.module.css
+++ /dev/null
@@ -1,6 +0,0 @@
-/**
- * Defines the CSS layers for the embedding SDK.
- */
-@layer embedding-sdk {
- @layer reset, vendor, main;
-}
diff --git a/frontend/src/metabase/embedding-sdk/css/vendor.module.css b/frontend/src/metabase/embedding-sdk/css/vendor.module.css
deleted file mode 100644
index a59ebdcc795..00000000000
--- a/frontend/src/metabase/embedding-sdk/css/vendor.module.css
+++ /dev/null
@@ -1,7 +0,0 @@
-/**
- * This file is not parsed as a CSS module, so all class names are unaffected
- * Layers are defined in the `layer.module.css`
- */
-@import "@mantine/core/styles.css" layer(embedding-sdk.vendor);
-@import "@mantine/dates/styles.css" layer(embedding-sdk.vendor);
-@import "../../css/vendor.css" layer(embedding-sdk.vendor);
diff --git a/package.json b/package.json
index 90369074d7b..46f4f6f0f26 100644
--- a/package.json
+++ b/package.json
@@ -314,6 +314,7 @@
"postcss-import": "15.1.0",
"postcss-loader": "7.0.2",
"postcss-nested": "^7.0.2",
+ "postcss-prefixwrap": "^1.56.2",
"postcss-preset-env": "^6.7.0",
"postcss-preset-mantine": "^1.17.0",
"postcss-styled-syntax": "^0.6.4",
diff --git a/postcss.config.js b/postcss.config.js
index 7fa2b98a224..ff88846d4dd 100644
--- a/postcss.config.js
+++ b/postcss.config.js
@@ -1,16 +1,22 @@
/* eslint-env node */
/* eslint-disable import/no-commonjs */
+const path = require("path");
+
const glob = require("glob");
-// eslint-disable-next-line no-undef
-const SRC_PATH = __dirname + "/frontend/src/metabase";
-const CSS_SRC = glob.sync(SRC_PATH + "/css/**/*.css");
+const SRC_PATH = path.join(__dirname, "frontend/src/metabase");
+const CSS_SRC = glob.sync(path.join(SRC_PATH, "css/**/*.css"));
module.exports = {
- plugins: {
- "postcss-import": {},
- "postcss-url": {},
- "postcss-preset-env": {
+ plugins: [
+ // Import other CSS files
+ require("postcss-import")(),
+
+ // Rebase/inline URLs
+ require("postcss-url")(),
+
+ // Modern CSS features & your custom-media definitions
+ require("postcss-preset-env")({
stage: 2,
importFrom: CSS_SRC,
features: {
@@ -19,9 +25,15 @@ module.exports = {
"focus-visible-pseudo-class": false,
"has-pseudo-class": false,
},
- },
- "postcss-discard-comments": {},
- "postcss-nesting": {},
- "postcss-preset-mantine": {},
- },
+ }),
+
+ // Strip comments
+ require("postcss-discard-comments")(),
+
+ // Nesting support
+ require("postcss-nesting")(),
+
+ // Mantine preset
+ require("postcss-preset-mantine")(),
+ ],
};
diff --git a/rspack.embedding-sdk-bundle.config.js b/rspack.embedding-sdk-bundle.config.js
index b965d38c109..2a9e9c47e91 100644
--- a/rspack.embedding-sdk-bundle.config.js
+++ b/rspack.embedding-sdk-bundle.config.js
@@ -5,12 +5,15 @@ const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
const rspack = require("@rspack/core");
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
+const prefixwrap = require("postcss-prefixwrap");
const mainConfig = require("./rspack.main.config");
const { resolve } = require("path");
const fs = require("fs");
const path = require("path");
+const postcssConfig = require("./postcss.config.js");
+
const {
TypescriptConvertErrorsToWarnings,
} = require("./frontend/build/embedding-sdk/rspack/typescript-convert-errors-to-warnings");
@@ -106,10 +109,37 @@ const config = {
},
{
test: /\.css$/,
- use: [
- { loader: "style-loader" },
- { loader: "css-loader", options: CSS_CONFIG },
- { loader: "postcss-loader" },
+ oneOf: [
+ // Scope SDK Mantine styles to the SDK to prevent leakage outside of the SDK
+ {
+ include: [/[\\/]@mantine[\\/].*\.css$/],
+ use: [
+ { loader: "style-loader" },
+ { loader: "css-loader", options: CSS_CONFIG },
+ {
+ loader: "postcss-loader",
+ options: {
+ postcssOptions: {
+ plugins: [
+ ...postcssConfig.plugins,
+ prefixwrap(":where(.mb-wrapper)", {
+ // We apply scope to selectors that start with `.m_`
+ // It skips some selectors like `[dir="ltr"] .m_*` but there's no ability to insert the `:where(.mb-wrapper)` between `[dir="ltr"]` and `.m_*`
+ ignoredSelectors: [/^(?!\.m_).*/],
+ }),
+ ],
+ },
+ },
+ },
+ ],
+ },
+ {
+ use: [
+ { loader: "style-loader" },
+ { loader: "css-loader", options: CSS_CONFIG },
+ { loader: "postcss-loader" },
+ ],
+ },
],
},
diff --git a/yarn.lock b/yarn.lock
index 5fee64c8b3d..795af10e670 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -16928,6 +16928,11 @@ postcss-place@^4.0.1:
postcss "^7.0.2"
postcss-values-parser "^2.0.0"
+postcss-prefixwrap@^1.56.2:
+ version "1.56.2"
+ resolved "https://registry.yarnpkg.com/postcss-prefixwrap/-/postcss-prefixwrap-1.56.2.tgz#fb94cc829afbbf39cceecb228644ad9b291add89"
+ integrity sha512-PnIsMX/VTtLYUrZe8Cex4vqXVvl5PUKbDbD52Wcp94ObZkt05oehCuOVvsUeig0eQoGOhTDBHfR8nnIkjf1/uA==
+
postcss-preset-env@^6.7.0:
version "6.7.0"
resolved "https://registry.yarnpkg.com/postcss-preset-env/-/postcss-preset-env-6.7.0.tgz#c34ddacf8f902383b35ad1e030f178f4cdf118a5"