The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat(sdk): adds `handleLink` to customize how links should be open (#64960)
Nicolò Pretto9ac8f80da8f7
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts b/enterprise/frontend/src/embedding-sdk-bundle/types/metabase-provider.tsindex ba755131ba7..49bb4dc3a25 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts@@ -4,7 +4,7 @@ import type { MetabaseTheme } from "metabase/embedding-sdk/theme";import type { MetabaseAuthConfig } from "./auth-config";import type { SdkEventHandlersConfig } from "./events";-import type { MetabasePluginsConfig } from "./plugins";+import type { MetabaseGlobalPluginsConfig } from "./plugins";import type { SdkErrorComponent } from "./ui";/**@@ -37,7 +37,7 @@ export interface MetabaseProviderProps {/*** See [Plugins](https://www.metabase.com/docs/latest/embedding/sdk/plugins).*/- pluginsConfig?: MetabasePluginsConfig;+ pluginsConfig?: MetabaseGlobalPluginsConfig;/*** See [Global event handlers](https://www.metabase.com/docs/latest/embedding/sdk/config#global-event-handlers).diff --git a/enterprise/frontend/src/embedding-sdk-bundle/types/plugins.ts b/enterprise/frontend/src/embedding-sdk-bundle/types/plugins.tsindex 13f59daadc3..5e004f4b853 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/types/plugins.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/types/plugins.ts@@ -52,3 +52,7 @@ export type MetabasePluginsConfig = {*/getNoObjectIllustration?: () => string | null | undefined;};++export type MetabaseGlobalPluginsConfig = MetabasePluginsConfig & {+ handleLink?: (url: string) => { handled: boolean };+};diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/plugins/HandleLinkPlugin.stories.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/plugins/HandleLinkPlugin.stories.tsxnew file mode 100644index 00000000000..fda6896276c--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/plugins/HandleLinkPlugin.stories.tsx@@ -0,0 +1,121 @@+import { useState } from "react";++import { getStorybookSdkAuthConfigForUser } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";+import { useCurrentUser } from "embedding-sdk-package/hooks/public/use-current-user";+import { getHostedBundleStoryDecorator } from "embedding-sdk-package/test/getHostedBundleStoryDecorator";++import { InteractiveQuestion } from "../InteractiveQuestion";+import { MetabaseProvider } from "../MetabaseProvider";++const config = getStorybookSdkAuthConfigForUser("admin");++export default {+ title: "EmbeddingSDK/Plugins/handleLink",+ parameters: {+ layout: "fullscreen",+ },+ decorators: [getHostedBundleStoryDecorator()],+ argTypes: {+ questionId: {+ control: { type: "number" },+ description: "Question ID with links to test handleLink plugin",+ },+ },+ args: {+ questionId: null,+ } as { questionId: number | null },+};++const QuestionNotice = () => {+ return (+ <div+ style={{+ padding: "20px",+ background: "#fff3cd",+ border: "1px solid #ffc107",+ marginBottom: "10px",+ }}+ >+ <p style={{ margin: 0 }}>+ <strong>Setup Instructions:</strong>{" "}+ {+ "This story requires a question id of a question with links. You can use "+ }+ <a+ href="http://metabase.localhost:3000/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImxpYi90eXBlIjoibWJxbC9xdWVyeSIsInN0YWdlcyI6W3sic291cmNlLXRhYmxlIjozLCJsaWIvdHlwZSI6Im1icWwuc3RhZ2UvbWJxbCIsImV4cHJlc3Npb25zIjpbWyJjb25jYXQiLHsibGliL3V1aWQiOiJjZDRlNDM5Yy00OTYwLTRlOWMtOGFkMy1iODQ2Mjk1ZjVmOGYiLCJlZmZlY3RpdmUtdHlwZSI6InR5cGUvVGV4dCIsImxpYi9leHByZXNzaW9uLW5hbWUiOiJHb29nbGUgaXQifSwiaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS9zZWFyY2g_cT1FQU4lMjAiLFsiZmllbGQiLHsibGliL3V1aWQiOiI2ODkxODJkOS0zNGMzLTQ5NGYtODk4NC1lNmUxODNmNzlmZDAiLCJlZmZlY3RpdmUtdHlwZSI6InR5cGUvVGV4dCIsImJhc2UtdHlwZSI6InR5cGUvVGV4dCJ9LDE1XV0sWyJjb25jYXQiLHsibGliL3V1aWQiOiJhNzMzZjNkNS1mZmNkLTQyMGYtOTMwNy1kMDlhOGM0MjBlMjgiLCJsaWIvZXhwcmVzc2lvbi1uYW1lIjoiQmluZyBpdCJ9LCJodHRwczovL3d3dy5iaW5nLmNvbS9zZWFyY2g_cT1FQU4lMjAiLFsiZmllbGQiLHsiZWZmZWN0aXZlLXR5cGUiOiJ0eXBlL1RleHQiLCJsaWIvdXVpZCI6ImI3ZTc2MGY3LTI3ZTktNDZiZS04NGVhLWZhMDIwOTRlMzUzMCIsImJhc2UtdHlwZSI6InR5cGUvVGV4dCJ9LDE1XV1dfV0sImRhdGFiYXNlIjoxfSwiZGlzcGxheSI6InRhYmxlIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e30sInR5cGUiOiJxdWVzdGlvbiJ9"+ target="_blank"+ rel="noopener noreferrer"+ >+ <strong>this question template</strong>+ </a>+ . Open it, save it to your Metabase instance, and then enter the+ question ID in the controls below.+ </p>+ </div>+ );+};++const AdminUserCheck = () => {+ const user = useCurrentUser();+ if (!(user as any)?.is_superuser) {+ return (+ <div+ style={{+ padding: "20px",+ background: "#fff3cd",+ border: "1px solid #ffc107",+ marginBottom: "10px",+ }}+ >+ {+ "The storybook user is not set as admin. You may not have the permission to access the question. Go to "+ }+ <a+ href="http://metabase.localhost:3000/admin/people"+ target="_blank"+ rel="noopener noreferrer"+ >+ http://metabase.localhost:3000/admin/people+ </a>+ {" and make "}+ <strong>[email protected]</strong>+ {" an admin."}+ </div>+ );+ }+ return null;+};++export const Default = ({ questionId }: { questionId: number }) => {+ const [selectedUrl, setSelectedUrl] = useState<string | null>(null);++ const handleLink = (url: string) => {+ setSelectedUrl(url);+ return { handled: true };+ };++ if (!questionId) {+ return <QuestionNotice />;+ }++ return (+ <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>+ {selectedUrl && (+ <div+ style={{+ padding: "20px",+ background: "#e8f5e9",+ border: "1px solid #4caf50",+ }}+ >+ <p>Selected URL: {selectedUrl}</p>+ </div>+ )}+ <MetabaseProvider authConfig={config} pluginsConfig={{ handleLink }}>+ <AdminUserCheck />++ <InteractiveQuestion questionId={questionId} />+ </MetabaseProvider>+ </div>+ );+};diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex 862e279d860..5f8f52310ea 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -104,6 +104,7 @@ export type {MetabaseDashboard,MetabaseDashboardPluginsConfig,MetabaseFontFamily,+ MetabaseGlobalPluginsConfig,MetabasePluginsConfig,MetabaseQuestion,MetabaseTheme,diff --git a/enterprise/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts b/enterprise/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.tsnew file mode 100644index 00000000000..8bd0f8da445--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-shared/lib/sdk-global-plugins.ts@@ -0,0 +1,38 @@+import { ensureMetabaseProviderPropsStore } from "./ensure-metabase-provider-props-store";++type HandleLinkFn = (url: string) => { handled: boolean };++type SdkGlobalPlugins = {+ handleLink?: HandleLinkFn;+};++// `MetabaseProvider` and most of the sdk code are in two different bundles,+// this means we can't use an exported object as singleton to share the global+// plugins between them. This function uses `ensureMetabaseProviderPropsStore`+// to access the provider props across bundles+export const getSdkGlobalPlugins = (): SdkGlobalPlugins => {+ return (+ ensureMetabaseProviderPropsStore().getState().props?.pluginsConfig || {}+ );+};++/**+ * Invokes the handleLink plugin if configured in the host app and returns an object with a 'handled' property, indicating if the host app handled the link.+ */+export function handleLinkSdkPlugin(url: string): { handled: boolean } {+ const globalPlugins = getSdkGlobalPlugins();++ if (!globalPlugins?.handleLink) {+ return { handled: false };+ }++ const result = globalPlugins.handleLink(url);++ if (!result || typeof result !== "object" || !("handled" in result)) {+ throw new Error(+ "handleLink plugin must return an object with a 'handled' property",+ );+ }++ return result;+}diff --git a/frontend/src/metabase/lib/dom.js b/frontend/src/metabase/lib/dom.jsindex 83f6e2336c8..550db2fb4cd 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 { handleLinkSdkPlugin } from "embedding-sdk-shared/lib/sdk-global-plugins";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { isCypressActive, isStorybookActive } from "metabase/env";import MetabaseSettings from "metabase/lib/settings";@@ -320,6 +321,12 @@ export function open() {url = ignoreSiteUrl ? url : getWithSiteUrl(url);+ // In the react sdk, allow the host app to override how to open links+ if (isEmbeddingSdk() && handleLinkSdkPlugin(url).handled) {+ // Plugin handled the link, don't continue with default behavior+ return;+ }+if (shouldOpenInBlankWindow(url, options)) {openInBlankWindow(url);} else if (isSameOrigin(url)) {diff --git a/frontend/src/metabase/lib/formatting/url.tsx b/frontend/src/metabase/lib/formatting/url.tsxindex 464a1a19bf7..bf6769e38bc 100644--- a/frontend/src/metabase/lib/formatting/url.tsx+++ b/frontend/src/metabase/lib/formatting/url.tsx@@ -1,5 +1,6 @@import cx from "classnames";+import { handleLinkSdkPlugin } from "embedding-sdk-shared/lib/sdk-global-plugins";import ExternalLink from "metabase/common/components/ExternalLink";import Link from "metabase/common/components/Link";import CS from "metabase/css/core/index.css";@@ -51,8 +52,19 @@ export function formatUrl(value: string, options: OptionsType = {}) {</Link>);}++ const onClickCaptureInSdk = isEmbeddingSdk()+ ? {+ onClickCapture: (e: React.MouseEvent<HTMLAnchorElement>) => {+ if (handleLinkSdkPlugin(url).handled) {+ e.preventDefault();+ }+ },+ }+ : {};+return (- <ExternalLink className={className} href={url}>+ <ExternalLink className={className} href={url} {...onClickCaptureInSdk}>{text}</ExternalLink>);diff --git a/frontend/test/metabase/lib/dom.unit.spec.js b/frontend/test/metabase/lib/dom.unit.spec.jsindex c6ef5a62da7..96bec68668d 100644--- a/frontend/test/metabase/lib/dom.unit.spec.js+++ b/frontend/test/metabase/lib/dom.unit.spec.js@@ -1,7 +1,9 @@+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";import {getSelectionPosition,getUrlTarget,+ open,parseDataUri,setSelectionPosition,shouldOpenInBlankWindow,@@ -95,3 +97,96 @@ describe("getUrlTarget", () => {expect(result).toBe("_blank");});});++describe("open()", () => {+ beforeEach(async () => {+ await mockIsEmbeddingSdk();+ // Ensure a clean store before each test+ ensureMetabaseProviderPropsStore().cleanup();+ });++ afterEach(() => {+ jest.restoreAllMocks();+ ensureMetabaseProviderPropsStore().cleanup();+ });++ it("should prevent default behavior when handleLink returns { handled: true }", () => {+ const handleLink = jest.fn().mockReturnValue({ handled: true });+ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const openInSameWindow = jest.fn();+ const openInBlankWindow = jest.fn();+ const url = "https://example.com/dashboard/1";++ open(url, {+ openInSameWindow,+ openInBlankWindow,+ });++ expect(handleLink).toHaveBeenCalledWith(url);+ expect(openInSameWindow).not.toHaveBeenCalled();+ expect(openInBlankWindow).not.toHaveBeenCalled();+ });++ it("should allow default behavior when handleLink returns { handled: false }", () => {+ const handleLink = jest.fn().mockReturnValue({ handled: false });+ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const openInSameWindow = jest.fn();+ const openInBlankWindow = jest.fn();+ const url = "https://example.com/dashboard/1";++ open(url, {+ openInSameWindow,+ openInBlankWindow,+ });++ expect(handleLink).toHaveBeenCalledWith(url);+ expect(openInBlankWindow).toHaveBeenCalledWith(url);+ });++ it("should throw error when handleLink returns invalid value", () => {+ const handleLink = jest.fn().mockReturnValue(true);+ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const openInSameWindow = jest.fn();+ const openInBlankWindow = jest.fn();+ const url = "https://example.com/dashboard/1";++ expect(() =>+ open(url, {+ openInSameWindow,+ openInBlankWindow,+ }),+ ).toThrow(+ "handleLink plugin must return an object with a 'handled' property",+ );++ expect(handleLink).toHaveBeenCalledWith(url);+ });++ it("should not call handleLink when not in embedding SDK", async () => {+ await mockIsEmbeddingSdk(false);+ const handleLink = jest.fn();+ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const openInSameWindow = jest.fn();+ const openInBlankWindow = jest.fn();+ const url = "https://example.com/dashboard/1";++ open(url, {+ openInSameWindow,+ openInBlankWindow,+ });++ expect(handleLink).not.toHaveBeenCalled();+ });+});diff --git a/frontend/test/metabase/lib/formatting/url.unit.spec.tsx b/frontend/test/metabase/lib/formatting/url.unit.spec.tsxnew file mode 100644index 00000000000..800247cd7ab--- /dev/null+++ b/frontend/test/metabase/lib/formatting/url.unit.spec.tsx@@ -0,0 +1,57 @@+import { render, screen } from "__support__/ui";+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";+import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";+import { formatUrl } from "metabase/lib/formatting/url";++describe("formatUrl", () => {+ afterEach(() => {+ ensureMetabaseProviderPropsStore().cleanup();+ jest.restoreAllMocks();+ });++ it("calls handleLinkSdkPlugin and prevents default in SDK", async () => {+ await mockIsEmbeddingSdk(true);++ const url = "https://example.com/dashboard/1";+ const handleLink = jest.fn().mockReturnValue({ handled: true });++ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const node = formatUrl(url, { jsx: true, rich: true, view_as: "link" });+ render(node as unknown as JSX.Element);++ const link = screen.getByRole("link");+ // Manually creating the event instead of using fireEvent.click because we need to inspect+ // the defaultPrevented property of the event.+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(event);++ expect(handleLink).toHaveBeenCalledWith(url);+ expect(event.defaultPrevented).toBe(true);+ });++ it("does not call handleLinkSdkPlugin in core app", async () => {+ await mockIsEmbeddingSdk(false);++ const url = "https://example.com/dashboard/2";+ const handleLink = jest.fn();++ ensureMetabaseProviderPropsStore().setProps({+ pluginsConfig: { handleLink },+ });++ const node = formatUrl(url, { jsx: true, rich: true, view_as: "link" });+ render(node as unknown as JSX.Element);++ const link = screen.getByRole("link");+ // Manually creating the event instead of using fireEvent.click because we need to inspect+ // the defaultPrevented property of the event.+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(event);++ expect(handleLink).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(false);+ });+});diff --git a/rspack.static-viz.config.js b/rspack.static-viz.config.jsindex c6a86e8d683..27976cc150d 100644--- a/rspack.static-viz.config.js+++ b/rspack.static-viz.config.js@@ -13,6 +13,8 @@ const CLJS_SRC_PATH_DEV = __dirname + "/target/cljs_dev";const LIB_SRC_PATH = __dirname + "/frontend/src/metabase-lib";const TYPES_SRC_PATH = __dirname + "/frontend/src/metabase-types";const EMBEDDING_SRC_PATH = __dirname + "/enterprise/frontend/src/embedding";+const SDK_SHARED_SRC_PATH =+ __dirname + "/enterprise/frontend/src/embedding-sdk-shared";const SDK_BUNDLE_SRC_PATH =__dirname + "/enterprise/frontend/src/embedding-sdk-bundle";const ENTERPRISE_SRC_PATH =@@ -122,6 +124,7 @@ module.exports = (env) => {"metabase-types": TYPES_SRC_PATH,embedding: EMBEDDING_SRC_PATH,"embedding-sdk-bundle": SDK_BUNDLE_SRC_PATH,+ "embedding-sdk-shared": SDK_SHARED_SRC_PATH,"process/browser": require.resolve("process/browser"),"ee-overrides":process.env.MB_EDITION === "ee"