Skip to content

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

make `mapQuestionClickActions` intercept links and fix links to host app (#64623)

Nicolò Prettobef6cb6908b4
diff --git a/e2e/test-component/scenarios/embedding-sdk/dashboard-click-behavior.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/dashboard-click-behavior.cy.spec.tsx
index aafadd94f2c..1f8484599d2 100644
--- a/e2e/test-component/scenarios/embedding-sdk/dashboard-click-behavior.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/dashboard-click-behavior.cy.spec.tsx
@@ -18,6 +18,11 @@ import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-
const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+/**
+ * NOTE: since https://github.com/metabase/metabase/pull/64623 we convert links to click behaviors,
+ * so this file is almost always checking for click behaviors and not anchor tags.
+ */
+
describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
beforeEach(() => {
signInAsAdminAndEnableEmbeddingSdk();
@@ -136,9 +141,7 @@ describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
it("should allow external URL click behaviors in the SDK (EMB-878)", () => {
// External click behaviour use the open() function in metabase/lib/dom creates temporary anchors and calls .click()
// To check that we call it, we stub the anchor element click
- cy.window().then((win) => {
- cy.stub(win.HTMLAnchorElement.prototype, "click").as("anchorClick");
- });
+ stubAnchorClick();
cy.get<string>("@dashboardId").then((dashboardId) => {
mountSdkContent(<InteractiveDashboard dashboardId={dashboardId} />);
@@ -241,6 +244,8 @@ describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
});
it("columns that return a string url should be rendered as a link", () => {
+ // We can't map them easily to click behaviors, so they stay as links for now
+ // see https://github.com/metabase/metabase/issues/64622
cy.get<string>("@questionId").then((questionId) => {
mountSdkContent(<InteractiveQuestion questionId={questionId} />);
});
@@ -248,12 +253,12 @@ describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
cy.intercept("GET", "/api/card/*").as("getCard");
cy.wait("@getCard");
- cy.findByRole("link", { name: "https://example.org/448" })
+ cy.findByRole("link", { name: "https://example.org/979" })
.should("have.length", 1)
- .should("have.attr", "href", "https://example.org/448");
+ .should("have.attr", "href", "https://example.org/979");
});
- it("columns that have 'type/URL' semantic type should be rendered as a link", () => {
+ it("columns that have 'type/URL' semantic type should open URL via click behavior", () => {
cy.signIn("admin");
cy.get<string>("@questionId").then((questionId) => {
@@ -300,23 +305,26 @@ describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
},
],
}).then(({ dashboard }) => {
+ stubAnchorClick();
+
mountSdkContent(
<InteractiveDashboard dashboardId={dashboard.id} />,
);
getSdkRoot().within(() => {
H.getDashboardCard(0)
- .findByRole("link", {
- name: "https://example.org/448",
- })
- .should("have.attr", "href", "https://example.org/448");
+ .findAllByText("https://example.org/761")
+ .first()
+ .click();
+
+ expectClickBehaviorForUrl("https://example.org/761");
});
});
});
});
});
- it("columns that have 'Display as Link' should be rendered as a link and use the custom rendering", () => {
+ it("columns that have 'Display as Link' should trigger custom URL click behavior", () => {
cy.signIn("admin");
cy.intercept("GET", "/api/card/*").as("getCard");
@@ -346,16 +354,77 @@ describe("scenarios > embedding-sdk > dashboard-click-behavior", () => {
},
],
}).then(({ dashboard }) => {
+ stubAnchorClick();
+
mountSdkContent(<EditableDashboard dashboardId={dashboard.id} />);
getSdkRoot().within(() => {
- H.getDashboardCard(0)
- .findByRole("link", {
- name: "Link to 448",
- })
- .should("have.attr", "href", "https://example.org/448");
+ H.getDashboardCard(0).findAllByText("Link to 493").first().click();
+
+ expectClickBehaviorForUrl("https://example.org/493");
+ });
+ });
+ });
+ });
+
+ it("links to the same domain as the host app should open in a new tab", () => {
+ cy.signIn("admin");
+ cy.intercept("GET", "/api/card/*").as("getCard");
+
+ cy.get<string>("@questionId").then((questionId) => {
+ H.createDashboardWithQuestions({
+ dashboardName: "URL Dashboard",
+ questions: [
+ {
+ name: "Orders with URLs",
+ query: {
+ "source-table": `card__${questionId}`,
+ limit: 5,
+ },
+ },
+ ],
+ cards: [
+ {
+ visualization_settings: {
+ column_settings: {
+ [JSON.stringify(["name", "ID"])]: {
+ view_as: "link",
+ link_text: "Link to {{ID}}",
+ // not super realistic, but we can't change the origin in component tests
+ link_url: `${window.location.origin}/test/{{ID}}`,
+ },
+ },
+ },
+ },
+ ],
+ }).then(({ dashboard }) => {
+ stubAnchorClick();
+
+ mountSdkContent(<EditableDashboard dashboardId={dashboard.id} />);
+
+ getSdkRoot().within(() => {
+ H.getDashboardCard(0).findAllByText("Link to 493").first().click();
+
+ expectClickBehaviorForUrl(`${window.location.origin}/test/493`);
});
});
});
});
});
+
+const stubAnchorClick = () => {
+ cy.window().then((win) => {
+ cy.stub(win.HTMLAnchorElement.prototype, "click").as("anchorClick");
+ });
+};
+
+const expectClickBehaviorForUrl = (url: string) => {
+ cy.get<sinon.SinonSpy>("@anchorClick").should((spy) => {
+ expect(spy.callCount).to.be.greaterThan(0);
+ const last = spy.getCalls().at(-1);
+ expect(last?.thisValue.target).to.eq("_blank");
+ const href = (last?.thisValue as HTMLAnchorElement).href;
+ const u = new URL(href);
+ expect(`${u.origin}${u.pathname}`).to.eq(url);
+ });
+};
diff --git a/e2e/test-component/scenarios/embedding-sdk/plugins.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/plugins.cy.spec.tsx
index 369522cacd9..87894199cd0 100644
--- a/e2e/test-component/scenarios/embedding-sdk/plugins.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/plugins.cy.spec.tsx
@@ -1,4 +1,5 @@
import { InteractiveDashboard } from "@metabase/embedding-sdk-react";
+import { useState } from "react";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
@@ -19,7 +20,7 @@ import type {
CustomClickActionWithCustomView,
} from "metabase/visualizations/types";
-const { ORDERS_ID, ORDERS, PEOPLE } = SAMPLE_DATABASE;
+const { ORDERS_ID, ORDERS, PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
const setup = (callback: () => void) => {
signInAsAdminAndEnableEmbeddingSdk();
@@ -217,4 +218,141 @@ describe("scenarios > embedding-sdk > plugins", () => {
});
});
});
+
+ describe("The `mapQuestionClickActions` plugin should intercept link clicks (EMB-890)", () => {
+ beforeEach(() => {
+ setup(() => {
+ cy.request("PUT", `/api/field/${PEOPLE.ADDRESS}`, {
+ semantic_type: "type/URL",
+ });
+
+ const questionWithAllLinkTypes: StructuredQuestionDetails = {
+ name: "Question with all link types",
+ query: {
+ "source-table": PEOPLE_ID,
+ fields: [
+ ["field", PEOPLE.ID, { "base-type": "type/BigInteger" }],
+ ["field", PEOPLE.NAME, { "base-type": "type/Text" }],
+ ["field", PEOPLE.STATE, { "base-type": "type/Text" }],
+ ["field", PEOPLE.ADDRESS, { "base-type": "type/Text" }],
+ ["expression", "url string", { "base-type": "type/Text" }],
+ ],
+ expressions: {
+ "url string": [
+ "concat",
+ "https://example.org/url/string/",
+ ["field", PEOPLE.ID, { "base-type": "type/BigInteger" }],
+ ],
+ },
+ limit: 5,
+ },
+ visualization_settings: {
+ column_settings: {
+ '["name","ID"]': {
+ view_as: "link", // viz setting -> view as "link"
+ column_title: "ID (display as link)",
+ link_text: "Link {{ID}}",
+ link_url: "https://example.org/display/as/link/{{ID}}",
+ },
+ '["name","ADDRESS"]': {
+ column_title: "ADDRESS (type/URL)",
+ },
+ '["name","NAME"]': {
+ click_behavior: {
+ type: "link",
+ linkType: "dashboard",
+ targetId: 1,
+ linkTextTemplate: "Internal link {{NAME}}",
+ },
+ column_title: "NAME (internal link - disabled)",
+ },
+ '["name","STATE"]': {
+ click_behavior: {
+ type: "link",
+ linkType: "url",
+ linkTextTemplate: "External {{STATE}}",
+ linkTemplate: "https://example.org/{{STATE}}",
+ },
+ column_title: "STATE (external URL)",
+ },
+ },
+ },
+ };
+
+ createDashboardWithQuestions({
+ dashboardName: "Dashboard with link columns",
+ questions: [questionWithAllLinkTypes],
+ cards: [{ size_x: 24, size_y: 6, col: 0, row: 0 }],
+ }).then(({ dashboard }) => {
+ cy.wrap(dashboard.id).as("dashboardId");
+ });
+ });
+ });
+
+ it("should call the immediate action if the plugin returns { onClick }", () => {
+ cy.get<string>("@dashboardId").then((dashboardId) => {
+ const onClickSpy = cy.spy().as("onClickSpy");
+
+ const Page = () => {
+ const [clickedColumn, setClickedColumn] = useState<string | null>(
+ null,
+ );
+ return (
+ <>
+ <p>
+ clicked column:
+ <span data-testid="clicked-column">{clickedColumn}</span>
+ </p>
+ <InteractiveDashboard
+ dashboardId={dashboardId}
+ plugins={{
+ mapQuestionClickActions: (
+ clickActions: ClickAction[],
+ clicked: MetabaseDataPointObject,
+ ) => {
+ return {
+ onClick: () => {
+ onClickSpy(clickActions, clicked);
+ setClickedColumn(clicked.column?.name ?? null);
+ },
+ };
+ },
+ }}
+ />
+ </>
+ );
+ };
+
+ mountSdkContent(<Page />);
+
+ getSdkRoot().within(() => {
+ cy.log('Test 1: ID column with view_as: "link"');
+ cy.findByText("Link 1").click();
+ cy.findByTestId("clicked-column").should("contain", "ID");
+ cy.findByTestId("click-actions-popover").should("not.exist");
+ cy.get("@onClickSpy").should("have.been.calledOnce");
+
+ cy.log("Test 2: ADDRESS column with semantic_type: type/URL");
+ cy.findByText("9611-9809 West Rosedale Road").click();
+ cy.findByTestId("clicked-column").should("contain", "ADDRESS");
+ cy.findByTestId("click-actions-popover").should("not.exist");
+ cy.get("@onClickSpy").should("have.been.calledTwice");
+
+ cy.log("Test 3: STATE with external URL click behavior");
+ cy.findByText("External NE").click();
+ cy.findByTestId("clicked-column").should("contain", "STATE");
+ cy.findByTestId("click-actions-popover").should("not.exist");
+ cy.get("@onClickSpy").should("have.been.calledThrice");
+
+ cy.log(
+ "Test 4: NAME with internal dashboard click behavior (disabled in SDK)",
+ );
+ cy.findByText("Hudson Borer").click();
+ cy.findByTestId("clicked-column").should("contain", "NAME");
+ cy.findByTestId("click-actions-popover").should("not.exist");
+ cy.get("@onClickSpy").should("have.callCount", 4);
+ });
+ });
+ });
+ });
});
diff --git a/frontend/src/metabase/embedding-sdk/lib/links.ts b/frontend/src/metabase/embedding-sdk/lib/links.ts
new file mode 100644
index 00000000000..1c3cac193f9
--- /dev/null
+++ b/frontend/src/metabase/embedding-sdk/lib/links.ts
@@ -0,0 +1,58 @@
+import type { VisualizationSettings } from "metabase-types/api";
+
+/**
+ * In modular embedding (react sdk and embed-js) we disable internal click behaviors
+ * but we want to keep external links (EMB-878) and clicking on the cell should fallback to
+ * drills if available (EMB-879)
+ */
+export function removeInternalClickBehaviors(
+ computedSettings: VisualizationSettings,
+) {
+ if (
+ computedSettings.click_behavior &&
+ computedSettings.click_behavior.type === "link" &&
+ computedSettings.click_behavior.linkType !== "url"
+ ) {
+ return {
+ ...computedSettings,
+ click_behavior: undefined,
+ };
+ }
+ return computedSettings;
+}
+
+/**
+ * Converts link columns to external click behaviors (EMB-890) We do this
+ * because click behaviors automatically support `mapQuestionClickActions`, and
+ * adding support for that to links would be a bigger effort than the remap
+ */
+export function convertLinkColumnToClickBehavior(
+ computedSettings: VisualizationSettings,
+) {
+ const isLinkColumn =
+ computedSettings.view_as === "link" ||
+ (computedSettings.column?.semantic_type === "type/URL" &&
+ computedSettings.view_as === "auto");
+
+ if (!isLinkColumn) {
+ return computedSettings;
+ }
+
+ const linkURL = computedSettings.link_url;
+ const linkText = computedSettings.link_text;
+ const colName = computedSettings.column?.name;
+
+ return {
+ ...computedSettings,
+ view_as: undefined,
+ link_url: undefined,
+ link_text: undefined,
+ click_behavior: {
+ type: "link",
+ linkType: "url",
+ linkTextTemplate:
+ linkText == null && colName ? `{{${colName}}}` : linkText,
+ linkTemplate: linkURL == null && colName ? `{{${colName}}}` : linkURL,
+ },
+ };
+}
diff --git a/frontend/src/metabase/lib/dom.js b/frontend/src/metabase/lib/dom.js
index 9b10ab75a86..83f6e2336c8 100644
--- a/frontend/src/metabase/lib/dom.js
+++ b/frontend/src/metabase/lib/dom.js
@@ -1,6 +1,7 @@
import querystring from "querystring";
import _ from "underscore";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { isCypressActive, isStorybookActive } from "metabase/env";
import MetabaseSettings from "metabase/lib/settings";
@@ -364,6 +365,10 @@ export function shouldOpenInBlankWindow(
blankOnDifferentOrigin = true,
} = {},
) {
+ if (isEmbeddingSdk()) {
+ // always open in new window in modular embedding (react SDK + EAJS)
+ return true;
+ }
const isMetaKey = event && event.metaKey != null ? event.metaKey : metaKey;
const isCtrlKey = event && event.ctrlKey != null ? event.ctrlKey : ctrlKey;
@@ -440,6 +445,10 @@ export function isSameOrSiteUrlOrigin(url) {
}
export function getUrlTarget(url) {
+ if (isEmbeddingSdk()) {
+ // always open in new window in modular embedding (react SDK + EAJS)
+ return "_blank";
+ }
return isSameOrSiteUrlOrigin(url) ? "_self" : "_blank";
}
diff --git a/frontend/src/metabase/lib/formatting/url.tsx b/frontend/src/metabase/lib/formatting/url.tsx
index 2a811891a90..464a1a19bf7 100644
--- a/frontend/src/metabase/lib/formatting/url.tsx
+++ b/frontend/src/metabase/lib/formatting/url.tsx
@@ -3,6 +3,7 @@ import cx from "classnames";
import ExternalLink from "metabase/common/components/ExternalLink";
import Link from "metabase/common/components/Link";
import CS from "metabase/css/core/index.css";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { isSameOrSiteUrlOrigin } from "metabase/lib/dom";
import { getDataFromClicked } from "metabase-lib/v1/parameters/utils/click-behavior";
import { isURL } from "metabase-lib/v1/types/utils/isa";
@@ -42,7 +43,8 @@ export function formatUrl(value: string, options: OptionsType = {}) {
const text = getLinkText(value, options);
const className = cx(CS.link, CS.linkWrappable);
- if (isSameOrSiteUrlOrigin(url)) {
+ // on the react sdk we treat all user provided urls as external links
+ if (isSameOrSiteUrlOrigin(url) && !isEmbeddingSdk()) {
return (
<Link className={className} to={url}>
{text}
diff --git a/frontend/src/metabase/visualizations/lib/settings.js b/frontend/src/metabase/visualizations/lib/settings.js
index 8544ef4b5e1..543b7fd9d91 100644
--- a/frontend/src/metabase/visualizations/lib/settings.js
+++ b/frontend/src/metabase/visualizations/lib/settings.js
@@ -1,6 +1,10 @@
import _ from "underscore";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import {
+ convertLinkColumnToClickBehavior,
+ removeInternalClickBehaviors,
+} from "metabase/embedding-sdk/lib/links";
import { ChartSettingColorPicker } from "metabase/visualizations/components/settings/ChartSettingColorPicker";
import ChartSettingColorsPicker from "metabase/visualizations/components/settings/ChartSettingColorsPicker";
import { ChartSettingFieldPicker } from "metabase/visualizations/components/settings/ChartSettingFieldPicker";
@@ -46,17 +50,12 @@ export function getComputedSettings(
extra,
);
}
- // In modular embedding (react sdk and embed-js) we disable internal click behaviors
- // but we want to keep external links (EMB-878) and clicking on the cell should fallback to
- // drills if available (EMB-879)
+
if (isEmbeddingSdk()) {
- if (
- computedSettings.click_behavior &&
- computedSettings.click_behavior.type === "link" &&
- computedSettings.click_behavior.linkType !== "url"
- ) {
- computedSettings.click_behavior = undefined;
- }
+ return _.compose(
+ removeInternalClickBehaviors,
+ convertLinkColumnToClickBehavior,
+ )(computedSettings);
}
return computedSettings;
diff --git a/frontend/test/metabase/lib/dom.unit.spec.js b/frontend/test/metabase/lib/dom.unit.spec.js
index 8fb187afab2..c6ef5a62da7 100644
--- a/frontend/test/metabase/lib/dom.unit.spec.js
+++ b/frontend/test/metabase/lib/dom.unit.spec.js
@@ -1,7 +1,10 @@
+import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";
import {
getSelectionPosition,
+ getUrlTarget,
parseDataUri,
setSelectionPosition,
+ shouldOpenInBlankWindow,
} from "metabase/lib/dom";
describe("getSelectionPosition/setSelectionPosition", () => {
@@ -54,3 +57,41 @@ describe("parseDataUri", () => {
expect(duration).toBeLessThan(1000);
});
});
+
+describe("shouldOpenInBlankWindow", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should return false for same origin links by default", () => {
+ const url = `${window.location.origin}/dashboard/1`;
+ const result = shouldOpenInBlankWindow(url);
+ expect(result).toBe(false);
+ });
+
+ it("should always return true when in embedding SDK", async () => {
+ await mockIsEmbeddingSdk();
+ const url = `${window.location.origin}/dashboard/1`;
+ const result = shouldOpenInBlankWindow(url);
+ expect(result).toBe(true);
+ });
+});
+
+describe("getUrlTarget", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should return _self for same origin links by default", () => {
+ const url = `${window.location.origin}/dashboard/1`;
+ const result = getUrlTarget(url);
+ expect(result).toBe("_self");
+ });
+
+ it("should always return _blank when in the embedding SDK", async () => {
+ await mockIsEmbeddingSdk();
+ const url = `${window.location.origin}/dashboard/1`;
+ const result = getUrlTarget(url);
+ expect(result).toBe("_blank");
+ });
+});