Skip to content

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

Implement proper column width measurement for custom font sizes (#71407)

Sébastien1511899a7edf
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts
index 87a66cd7be0..318262f4d97 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts
@@ -1,4 +1,7 @@
-import { ORDERS_DASHBOARD_ID } from "e2e/support/cypress_sample_instance_data";
+import {
+ ORDERS_DASHBOARD_ID,
+ ORDERS_QUESTION_ID,
+} from "e2e/support/cypress_sample_instance_data";
import type { MetabaseTheme } from "metabase/embedding-sdk/theme/MetabaseTheme";
const { H } = cy;
@@ -69,6 +72,65 @@ describe("scenarios > embedding > sdk iframe embedding > theming", () => {
});
});
+ it("should measure table column widths based on themed font size", () => {
+ const SMALL_FONT_THEME = {
+ components: {
+ table: { cell: { fontSize: "10px" } },
+ },
+ } as const satisfies MetabaseTheme;
+
+ let defaultColumnWidth: number;
+
+ cy.log("1. load with default theme and measure column width");
+
+ const defaultFrame = H.loadSdkIframeEmbedTestPage({
+ elements: [
+ {
+ component: "metabase-question",
+ attributes: { questionId: ORDERS_QUESTION_ID },
+ },
+ ],
+ });
+
+ cy.wait("@getCardQuery");
+
+ defaultFrame.within(() => {
+ cy.findAllByTestId("header-cell")
+ .filter(":contains('Product ID')")
+ .first()
+ .then(($el) => {
+ defaultColumnWidth = $el[0].getBoundingClientRect().width;
+ expect(defaultColumnWidth).to.be.greaterThan(0);
+ });
+ });
+
+ cy.log("2. load with smaller font theme and verify column is narrower");
+
+ const themedFrame = H.loadSdkIframeEmbedTestPage({
+ elements: [
+ {
+ component: "metabase-question",
+ attributes: { questionId: ORDERS_QUESTION_ID },
+ },
+ ],
+ metabaseConfig: {
+ theme: SMALL_FONT_THEME,
+ },
+ });
+
+ cy.wait("@getCardQuery");
+
+ themedFrame.within(() => {
+ cy.findAllByTestId("header-cell")
+ .filter(":contains('Product ID')")
+ .first()
+ .then(($el) => {
+ const themedColumnWidth = $el[0].getBoundingClientRect().width;
+ expect(themedColumnWidth).to.be.lessThan(defaultColumnWidth);
+ });
+ });
+ });
+
it("should handle dynamic theme updates", () => {
const THEME_SWITCHER_HTML = `
<div>
diff --git a/frontend/src/metabase/data-grid/hooks/use-body-cell-measure.tsx b/frontend/src/metabase/data-grid/hooks/use-body-cell-measure.tsx
index a8595ee8555..2b617dc617f 100644
--- a/frontend/src/metabase/data-grid/hooks/use-body-cell-measure.tsx
+++ b/frontend/src/metabase/data-grid/hooks/use-body-cell-measure.tsx
@@ -22,6 +22,7 @@ export interface CellSize {
export const useCellMeasure = (
cell: React.ReactNode,
contentNodeSelector: string,
+ fontSize?: string,
) => {
const rootRef = useRef<HTMLDivElement>(null);
@@ -37,14 +38,14 @@ export const useCellMeasure = (
visibility: "hidden",
pointerEvents: "none",
zIndex: -999,
- fontSize: DEFAULT_FONT_SIZE,
+ fontSize: fontSize ?? DEFAULT_FONT_SIZE,
overflow: "visible",
}}
>
{cell}
</div>
);
- }, [cell]);
+ }, [cell, fontSize]);
const measureDimensions: CellMeasurer = useCallback(
(content: React.ReactNode, containerWidth?: number) => {
@@ -93,10 +94,15 @@ export const useBodyCellMeasure = (theme?: DataGridTheme) => {
),
[theme?.fontSize],
);
+
const {
measureDimensions: measureBodyCellDimensions,
measureRoot: measureBodyCellRoot,
- } = useCellMeasure(bodyCellToMeasure, "[data-grid-cell-content]");
+ } = useCellMeasure(
+ bodyCellToMeasure,
+ "[data-grid-cell-content]",
+ theme?.fontSize,
+ );
const measureRoot = useMemo(
() => createPortal(measureBodyCellRoot, getPortalRootElement()),
diff --git a/frontend/src/metabase/data-grid/hooks/use-measure-column-widths.tsx b/frontend/src/metabase/data-grid/hooks/use-measure-column-widths.tsx
index 25d9c2df45f..a48f1ace620 100644
--- a/frontend/src/metabase/data-grid/hooks/use-measure-column-widths.tsx
+++ b/frontend/src/metabase/data-grid/hooks/use-measure-column-widths.tsx
@@ -42,7 +42,9 @@ export const useMeasureColumnWidths = <TData, TValue>(
) => {
const measureColumnWidths = useCallback(
(onMeasured: (columnSizingState: ColumnSizingState) => void) => {
- const measureRoot = createMeasurementContainer();
+ const measureRoot = createMeasurementContainer({
+ fontSize: theme?.fontSize,
+ });
let measureRootTree: Root | undefined = undefined;
const onMeasureHeaderRender = (div: HTMLDivElement) => {
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
index 338c82bdc91..63a36fc0903 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
@@ -673,8 +673,8 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
]);
const dataGridTheme: DataGridTheme = useMemo(
- () => tableThemeToDataGridTheme(tableTheme),
- [tableTheme],
+ () => tableThemeToDataGridTheme(tableTheme, theme?.other?.fontSize),
+ [tableTheme, theme?.other?.fontSize],
);
const dataGridStyles: DataGridStylesProps["styles"] = useMemo(() => {
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.ts
new file mode 100644
index 00000000000..b2324926818
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.ts
@@ -0,0 +1,52 @@
+/**
+ * Resolves a CSS font-size value from em units to px, given a base font size
+ * in px. This is needed because measurement containers are appended to
+ * document.body, where em values would resolve against the body's font-size
+ * instead of the embedding SDK root's font-size.
+ *
+ * Only em values are converted — rem values are left as-is because they always
+ * resolve against the root <html> element regardless of DOM position, so they
+ * produce the same px result in both the measurement container and the actual
+ * rendered table.
+ *
+ * The conversion is only performed when baseFontSize is in px, since we can
+ * only do reliable arithmetic with known absolute units.
+ */
+export function resolveFontSizeToPx(
+ fontSize: string,
+ baseFontSize?: string,
+): string {
+ const isRem = fontSize.endsWith("rem");
+ const isEm = fontSize.endsWith("em") && !isRem;
+
+ if (!isEm) {
+ console.warn(
+ `resolveFontSizeToPx: fontSize "${fontSize}" is not in em. ` +
+ `Column width measurement may be inaccurate.`,
+ );
+ return fontSize;
+ }
+
+ if (!baseFontSize || !baseFontSize.endsWith("px")) {
+ console.warn(
+ `resolveFontSizeToPx: cannot convert "${fontSize}" to px — ` +
+ `baseFontSize ${baseFontSize ? `"${baseFontSize}" is not in px` : "is not provided"}. ` +
+ `Column width measurement may be inaccurate.`,
+ );
+ return fontSize;
+ }
+
+ const emValue = parseFloat(fontSize);
+ const baseValue = parseFloat(baseFontSize);
+
+ if (isNaN(emValue) || isNaN(baseValue)) {
+ console.warn(
+ `resolveFontSizeToPx: cannot parse "${fontSize}" or "${baseFontSize}" as numbers. ` +
+ `Column width measurement may be inaccurate.`,
+ );
+ return fontSize;
+ }
+
+ const pxValue = Math.round(emValue * baseValue * 100) / 100;
+ return `${pxValue}px`;
+}
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.unit.spec.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.unit.spec.ts
new file mode 100644
index 00000000000..2cbf46880d4
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/resolve-font-size-to-px.unit.spec.ts
@@ -0,0 +1,65 @@
+import { resolveFontSizeToPx } from "./resolve-font-size-to-px";
+
+describe("resolveFontSizeToPx", () => {
+ let consoleWarnSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleWarnSpy.mockRestore();
+ });
+
+ it("converts em to px using the base font size", () => {
+ expect(resolveFontSizeToPx("0.893em", "14px")).toBe("12.5px");
+ expect(consoleWarnSpy).not.toHaveBeenCalled();
+ });
+
+ it("rounds to two decimal places", () => {
+ expect(resolveFontSizeToPx("0.857em", "14px")).toBe("12px");
+ expect(resolveFontSizeToPx("0.933em", "15px")).toBe("14px");
+ });
+
+ it("warns and returns px values unchanged", () => {
+ expect(resolveFontSizeToPx("12.5px", "14px")).toBe("12.5px");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not in em"),
+ );
+ });
+
+ it("warns and returns the original value when no base font size is provided", () => {
+ expect(resolveFontSizeToPx("0.893em")).toBe("0.893em");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not provided"),
+ );
+ });
+
+ it("warns and returns rem values unchanged", () => {
+ expect(resolveFontSizeToPx("1rem", "14px")).toBe("1rem");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not in em"),
+ );
+ });
+
+ it("warns for unrecognized font-size units", () => {
+ expect(resolveFontSizeToPx("inherit", "14px")).toBe("inherit");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not in em"),
+ );
+ });
+
+ it("warns and does not convert when baseFontSize is in em", () => {
+ expect(resolveFontSizeToPx("0.893em", "0.875em")).toBe("0.893em");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not in px"),
+ );
+ });
+
+ it("warns and does not convert when baseFontSize is in rem", () => {
+ expect(resolveFontSizeToPx("0.893em", "2rem")).toBe("0.893em");
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("is not in px"),
+ );
+ });
+});
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
index bce4677bba0..b40652dd8d9 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
@@ -1,12 +1,15 @@
import type { DataGridTheme } from "metabase/data-grid/types";
import type { MantineTheme } from "metabase/ui";
+import { resolveFontSizeToPx } from "./resolve-font-size-to-px";
+
export function tableThemeToDataGridTheme(
tableTheme: MantineTheme["other"]["table"],
+ baseFontSize?: string,
): DataGridTheme {
return {
stickyBackgroundColor: tableTheme.stickyBackgroundColor,
- fontSize: tableTheme.cell.fontSize,
+ fontSize: resolveFontSizeToPx(tableTheme.cell.fontSize, baseFontSize),
cell: {
backgroundColor:
tableTheme.cell.backgroundColor ?? "var(--mb-color-background-primary)",
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
index 30a9ef83b3b..39a81b705e7 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
@@ -65,4 +65,21 @@ describe("tableThemeToDataGridTheme", () => {
textColor: undefined,
});
});
+
+ it("resolves em fontSize to px when baseFontSize is provided", () => {
+ const themeWithEmFontSize = {
+ ...mockTableTheme,
+ cell: { ...mockTableTheme.cell, fontSize: "0.893em" },
+ };
+
+ const result = tableThemeToDataGridTheme(themeWithEmFontSize, "14px");
+
+ expect(result.fontSize).toBe("12.5px");
+ });
+
+ it("keeps px fontSize unchanged when baseFontSize is provided", () => {
+ const result = tableThemeToDataGridTheme(mockTableTheme, "14px");
+
+ expect(result.fontSize).toBe("14px");
+ });
});