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
Hide public link options from non-admins and when public sharing is disabled (#75681)
Andrei Chernykhe49ba026212c
diff --git a/e2e/test/scenarios/permissions/application-permissions.cy.spec.js b/e2e/test/scenarios/permissions/application-permissions.cy.spec.jsindex 650884185ab..1b2ab6612c5 100644--- a/e2e/test/scenarios/permissions/application-permissions.cy.spec.js+++ b/e2e/test/scenarios/permissions/application-permissions.cy.spec.js@@ -69,7 +69,8 @@ describe("scenarios > admin > permissions > application", () => {H.visitQuestion(ORDERS_QUESTION_ID);H.tableInteractive().should("be.visible");- H.sharingMenuButton().should("be.disabled");+ // No public link: the share button only copies the app link, no menu.+ H.sharingMenuButton().should("have.attr", "aria-label", "Copy link");cy.visit("/account/notifications");cy.findByTestId("notifications-list").within(() => {diff --git a/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js b/e2e/test/scenarios/sharing/public-dashboard.cy.spec.jsindex d2289ff8a54..171cab1063d 100644--- a/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js@@ -133,31 +133,6 @@ describe("scenarios > public > dashboard", () => {});});- it("should only allow non-admin users to see a public link if one has already been created", () => {- cy.get("@dashboardId").then((id) => {- H.createPublicDashboardLink(id);- cy.signOut();- });-- cy.signInAsNormalUser().then(() => {- H.visitDashboard("@dashboardId");- H.openSharingMenu("Public link");-- cy.findByTestId("public-link-popover-content").within(() => {- cy.findByText("Public link").should("be.visible");- cy.findByTestId("public-link-input").should(- "not.have.attr",- "placeholder",- "Loading…",- );- cy.findByTestId("public-link-input").should(($input) => {- expect($input.val()).to.match(PUBLIC_DASHBOARD_REGEX);- });- cy.findByText("Remove public URL").should("not.exist");- });- });- });-Object.entries(USERS).map(([userType, setUser]) =>describe(`${userType}`, () => {it("should be able to view public dashboards", () => {diff --git a/e2e/test/scenarios/sharing/public-question.cy.spec.js b/e2e/test/scenarios/sharing/public-question.cy.spec.jsindex 1465c663c7c..baac3c36acc 100644--- a/e2e/test/scenarios/sharing/public-question.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-question.cy.spec.js@@ -81,26 +81,6 @@ describe("scenarios > public > question", () => {});});- it("should only allow non-admin users to see a public link if one has already been created", () => {- H.createNativeQuestion(questionData).then(({ body: { id } }) => {- H.createPublicQuestionLink(id);- cy.signOut();- cy.signInAsNormalUser().then(() => {- H.visitQuestion(id);-- H.openSharingMenu("Public link");-- cy.findByTestId("public-link-popover-content").within(() => {- cy.findByText("Public link").should("be.visible");- cy.findByTestId("public-link-input").should(($input) => {- expect($input.val()).to.match(PUBLIC_QUESTION_REGEX);- });- cy.findByText("Remove public URL").should("not.exist");- });- });- });- });-Object.entries(USERS).map(([userType, setUser]) =>describe(`${userType}`, () => {it("should be able to view public questions", () => {diff --git a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.jsindex 65427d4fe8e..309928b65b3 100644--- a/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-sharing-embed-button-behavior.cy.spec.js@@ -47,8 +47,19 @@ const { H } = cy;visitResource(resource, id);});- H.openSharingMenu();- H.sharingMenu().findByText(/embed/i).should("not.exist");+ if (resource === "question") {+ // No public link: the share button copies directly, so there's no menu.+ H.sharingMenuButton().should(+ "have.attr",+ "aria-label",+ "Copy link",+ );+ }++ if (resource === "dashboard") {+ H.openSharingMenu();+ H.sharingMenu().findByText(/embed/i).should("not.exist");+ }});});});@@ -83,41 +94,42 @@ const { H } = cy;});describe("when user is non-admin", () => {- it(`should show a disabled public link button if the ${resource} doesn't have a public link`, () => {+ it(`should not prompt a non-admin to create a public link for a ${resource} without an existing link`, () => {cy.signInAsNormalUser();cy.get("@resourceId").then((id) => {visitResource(resource, id);});- H.openSharingMenu();- H.sharingMenu().findByText(- "Ask your admin to create a public link",- );+ assertNonAdminCannotCreatePublicLink(resource);});- it(`should show the public link button if the ${resource} has a public link`, () => {+ it(`should let a non-admin copy the existing public link for a ${resource}`, () => {cy.get("@resourceId").then((id) => {createPublicResourceLink(resource, id);- visitResource(resource, id);});- H.openSharingMenu(/public link/i);-- assertValidPublicLink({ resource, shouldHaveRemoveLink: true });-cy.signInAsNormalUser();cy.get("@resourceId").then((id) => {visitResource(resource, id);});- H.openSharingMenu("Public link");+ cy.window().then((win) => {+ cy.stub(win.navigator.clipboard, "writeText")+ .as("copyLink")+ .resolves();+ });- assertValidPublicLink({- resource,- shouldHaveRemoveLink: false,+ H.openSharingMenu("Copy public link");+ H.tooltip().findByText("Public link copied to clipboard");++ cy.get("@copyLink").should((stub) => {+ expect(stub.firstCall.args[0]).to.match(+ new RegExp(`/public/${resource}/`),+ );});+ cy.findByTestId("public-link-popover-content").should("not.exist");});});});@@ -129,7 +141,7 @@ const { H } = cy;});describe("when user is admin", () => {- it(`should show a disabled menu item for public links for ${resource} and allow the user to access the embed modal`, () => {+ it(`should hide the public link option for ${resource} and allow the user to access the embed modal`, () => {cy.get("@resourceId").then((id) => {visitResource(resource, id);});@@ -137,26 +149,23 @@ const { H } = cy;H.openSharingMenu();H.sharingMenu().within(() => {- cy.findByText("Public link").should("be.visible");- cy.findByText("Enable").should("be.visible");+ cy.findByText(/public link/i).should("not.exist");+ cy.findByText("Enable").should("not.exist");});- cy.findByTestId("embed-menu-embed-modal-item").click();+ H.sharingMenu().findByRole("menuitem", { name: "Embed" }).click();});});describe("when user is non-admin", () => {- it(`should show a disabled button for ${resource}`, () => {+ it(`should not prompt a non-admin to create a public link for ${resource}`, () => {cy.signInAsNormalUser();cy.get("@resourceId").then((id) => {visitResource(resource, id);});- H.openSharingMenu();- H.sharingMenu().findByText(- "Ask your admin to create a public link",- );+ assertNonAdminCannotCreatePublicLink(resource);});});});@@ -1019,6 +1028,24 @@ function visitResource(resource, id) {}}+function assertNonAdminCannotCreatePublicLink(resource) {+ if (resource === "question") {+ // No public link: the share button copies the app link directly, no menu.+ H.sharingMenuButton().should("have.attr", "aria-label", "Copy link");+ }++ if (resource === "dashboard") {+ // No public link: dashboards keep the app link copy and the PDF export.+ H.openSharingMenu();+ H.sharingMenu().within(() => {+ cy.findByText("Copy link").should("be.visible");+ cy.findByText("Export as PDF").should("be.visible");+ cy.findByText("Embed").should("not.exist");+ cy.findByText(/public link/i).should("not.exist");+ });+ }+}+function assertValidPublicLink({ resource, shouldHaveRemoveLink }) {const regex = new RegExp(`https?:\\/\\/[^\\/]+\\/public\\/${resource}\\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(\\.csv|\\.json|\\.xlsx)?`,diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.jsindex b6ca2a36027..ccdc4a0522a 100644--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js@@ -970,7 +970,7 @@ describe("issue 16108", () => {cy.icon("download").realHover();H.tooltip().findByText("Download results");H.sharingMenuButton().realHover();- H.tooltip().findByText("Sharing");+ H.tooltip().findByText("Share");});});diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsxindex cb03f228439..49347a66428 100644--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx@@ -154,11 +154,22 @@ describe("SCIM User Provisioning Settings", () => {settings: {"scim-enabled": true,},+ settingDefinitions: [+ {+ key: "scim-base-url",+ is_env_setting: false,+ env_name: "",+ value: "https://example.com/api/ee/scim/v2",+ },+ ],});- await userEvent.click(screen.getByLabelText("copy icon"));+ await userEvent.click(await screen.findByLabelText("copy icon"));expect(await screen.findByText("Copied!")).toBeInTheDocument();+ expect(window.navigator.clipboard.writeText).toHaveBeenCalledWith(+ "https://example.com/api/ee/scim/v2",+ );});it("should call the regenerate token endpoint", async () => {diff --git a/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsxindex 56b1434afb2..0af4af46e59 100644--- a/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx+++ b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx@@ -17,9 +17,10 @@ export const CopyTextInput = forwardRef(function CopyTextInput({classNames,onClick,+ onCopied,readOnly,...props- }: TextInputProps & { value: string },+ }: TextInputProps & { value: string; onCopied?: () => void },ref: Ref<HTMLInputElement>,) {const isReadOnly = readOnly ?? defaultProps.readOnly;@@ -42,15 +43,25 @@ export const CopyTextInput = forwardRef(function CopyTextInput(}}rightSectionPointerEvents="all"rightSection={- <CopyButton value={props.value} timeout={2000}>- {({ copied, copy }) => (- <Tooltip label={t`Copied!`} opened={copied}>- <ActionIcon variant="subtle" aria-label={t`Copy`} onClick={copy}>- <Icon name="copy" />- </ActionIcon>- </Tooltip>- )}- </CopyButton>+ props.value ? (+ <CopyButton value={props.value} timeout={2000}>+ {({ copied, copy }) => (+ <Tooltip label={t`Copied!`} opened={copied}>+ <ActionIcon+ variant="subtle"+ aria-label={t`Copy`}+ data-testid="copy-button"+ onClick={() => {+ copy();+ onCopied?.();+ }}+ >+ <Icon name="copy" />+ </ActionIcon>+ </Tooltip>+ )}+ </CopyButton>+ ) : undefined}/>);diff --git a/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.unit.spec.tsx b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.unit.spec.tsxnew file mode 100644index 00000000000..3d91cdc0a51--- /dev/null+++ b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.unit.spec.tsx@@ -0,0 +1,29 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";++import { CopyTextInput } from "./CopyTextInput";++describe("CopyTextInput", () => {+ it("copies the value and calls onCopy when clicking the copy button", async () => {+ jest.mocked(navigator.clipboard.writeText).mockClear();+ const onCopied = jest.fn();+ renderWithProviders(+ <CopyTextInput value="https://example.com" onCopied={onCopied} />,+ );++ await userEvent.click(screen.getByTestId("copy-button"));++ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "https://example.com",+ );+ expect(onCopied).toHaveBeenCalled();+ });++ it("does not render the copy button when there is nothing to copy", () => {+ renderWithProviders(<CopyTextInput value="" placeholder="Loading…" />);++ expect(screen.getByPlaceholderText("Loading…")).toBeInTheDocument();+ expect(screen.queryByTestId("copy-button")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsxindex dd9e97e57c2..6ba1c9ee92a 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardHeaderButtonRow.unit.spec.tsx@@ -69,7 +69,7 @@ const DASHBOARD_EXPECTED_DATA_MAP: Record<},[DASHBOARD_ACTION.DASHBOARD_SHARING]: {icon: "share",- tooltip: "Sharing",+ tooltip: "Share",},[DASHBOARD_ACTION.REFRESH_WIDGET]: {icon: "clock",diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsxindex 552feaf0d1a..b5f71a3caa7 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx@@ -1,5 +1,13 @@import { isInstanceAnalyticsCollection } from "metabase/collections/utils";-import { getIsDashCardsRunning } from "metabase/dashboard/selectors";+import { useSetting } from "metabase/common/hooks";+import {+ getIsDashCardsRunning,+ getSelectedTabId,+} from "metabase/dashboard/selectors";+import {+ CopyLinkMenuItem,+ CopyPublicLinkMenuItem,+} from "metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem";import { EmbedMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem";import { ExportPdfMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/ExportPdfMenuItem";import { PublicLinkMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem";@@ -7,54 +15,104 @@ import { SharingMenu } from "metabase/embedding/components/SharingMenu/SharingMeimport type { DashboardSharingModalType } from "metabase/embedding/components/SharingMenu/types";import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useSharingModal } from "metabase/embedding/hooks/use-sharing-modal";+import { trackPublicLinkCopied } from "metabase/embedding/lib/analytics";import { useSelector } from "metabase/redux";-import { Box, Flex, Menu } from "metabase/ui";+import { getUserIsAdmin } from "metabase/selectors/user";+import { Box, Flex } from "metabase/ui";+import {+ dashboard as getDashboardUrl,+ publicDashboard as getPublicDashboardUrl,+} from "metabase/urls";import type { Dashboard } from "metabase-types/api";import { DashboardPublicLinkPopover } from "../../../DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover";export function DashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {+ const isAdmin = useSelector(getUserIsAdmin);++ if (dashboard.archived) {+ return null;+ }++ return isAdmin ? (+ <AdminDashboardSharingMenu dashboard={dashboard} />+ ) : (+ <NonAdminDashboardSharingMenu dashboard={dashboard} />+ );+}++// Copies the app link, pointing at the tab the user is looking at when there is one.+function CopyDashboardLinkMenuItem({ dashboard }: { dashboard: Dashboard }) {+ const siteUrl = useSetting("site-url");+ const selectedTabId = useSelector(getSelectedTabId);+ const hasMultipleTabs = (dashboard.tabs?.length ?? 0) > 1;+ const tabId =+ hasMultipleTabs && selectedTabId != null ? selectedTabId : undefined;++ return (+ <CopyLinkMenuItem+ url={`${siteUrl}${getDashboardUrl(dashboard, { tabId })}`}+ />+ );+}++function AdminDashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {const { modalType, setModalType } =useSharingModal<DashboardSharingModalType>({resource: dashboard,resourceType: "dashboard",});-- const hasPublicLink = !!dashboard?.public_uuid;- const isArchived = dashboard.archived;+ const isDashCardsRunning = useSelector(getIsDashCardsRunning);+ const isPublicSharingEnabled = useSetting("enable-public-sharing");const isAnalytics =dashboard.collection && isInstanceAnalyticsCollection(dashboard.collection);-const canShare = !isAnalytics;- const isDashCardsRunning = useSelector(getIsDashCardsRunning);-- if (isArchived) {- return null;- }return (<Flex><SharingMenu>- <ExportPdfMenuItem dashboard={dashboard} loading={isDashCardsRunning} />+ <CopyDashboardLinkMenuItem dashboard={dashboard} />+ {canShare && isPublicSharingEnabled && (+ <PublicLinkMenuItem+ hasPublicLink={Boolean(dashboard.public_uuid)}+ onClick={() => setModalType("dashboard-public-link")}+ />+ )}{canShare && (- <>- <Menu.Divider />- <PublicLinkMenuItem- hasPublicLink={hasPublicLink}- onClick={() => setModalType("dashboard-public-link")}- />- <EmbedMenuItem- onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}- />- </>+ <EmbedMenuItem+ onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}+ />)}+ <ExportPdfMenuItem dashboard={dashboard} loading={isDashCardsRunning} /></SharingMenu>- <DashboardPublicLinkPopover- dashboard={dashboard}- target={<Box h="2rem" />}- isOpen={modalType === "dashboard-public-link"}- onClose={() => setModalType(null)}- />+ {modalType === "dashboard-public-link" && (+ <DashboardPublicLinkPopover+ dashboard={dashboard}+ target={<Box h="2rem" />}+ isOpen+ onClose={() => setModalType(null)}+ />+ )}</Flex>);}++// Non-admins can't create public links or embeds; they get the app link copy,+// the PDF export, and a public link copy when one already exists.+function NonAdminDashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {+ const isDashCardsRunning = useSelector(getIsDashCardsRunning);+ const publicUuid = dashboard.public_uuid;++ return (+ <SharingMenu>+ <CopyDashboardLinkMenuItem dashboard={dashboard} />+ {publicUuid && (+ <CopyPublicLinkMenuItem+ url={getPublicDashboardUrl(publicUuid)}+ onCopied={() => trackPublicLinkCopied({ artifact: "dashboard" })}+ />+ )}+ <ExportPdfMenuItem dashboard={dashboard} loading={isDashCardsRunning} />+ </SharingMenu>+ );+}diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsxindex 2805305c682..6b97cd30de4 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx@@ -1,15 +1,22 @@-import { screen } from "__support__/ui";+import userEvent from "@testing-library/user-event";++import { screen, waitFor } from "__support__/ui";+import { createMockDashboardTab } from "metabase-types/api/mocks";import { openMenu, setupDashboardSharingMenu } from "./tests/setup";describe("DashboardSharingMenu", () => {- it("should have a 'sharing' tooltip by default", () => {+ beforeEach(() => {+ jest.mocked(navigator.clipboard.writeText).mockClear();+ });++ it("should have a 'share' tooltip by default", () => {setupDashboardSharingMenu({isAdmin: true,});expect(screen.getByTestId("sharing-menu-button")).toHaveAttribute("aria-label",- "Sharing",+ "Share",);});@@ -35,9 +42,9 @@ describe("DashboardSharingMenu", () => {isAdmin: userType === "admin",dashboard: {tabs: [- { id: 1, name: "First Tab" },- { id: 2, name: "Second Tab" },- ] as any,+ createMockDashboardTab({ id: 1, name: "First Tab" }),+ createMockDashboardTab({ id: 2, name: "Second Tab" }),+ ],},});await openMenu();@@ -97,59 +104,152 @@ describe("DashboardSharingMenu", () => {).not.toBeInTheDocument();});- it('should show an "Enable" link if public sharing is disabled', async () => {+ it("should hide the public link option if public sharing is disabled", async () => {setupDashboardSharingMenu({isAdmin: true,isPublicSharingEnabled: false,});await openMenu();- expect(screen.getByText("Public link")).toBeInTheDocument();- expect(screen.getByText("Enable")).toBeInTheDocument();+ expect(screen.queryByText("Public link")).not.toBeInTheDocument();+ expect(screen.queryByText("Enable")).not.toBeInTheDocument();expect(screen.queryByText("Create a public link"),).not.toBeInTheDocument();+ expect(screen.getByText("Export as PDF")).toBeInTheDocument();+ expect(screen.getByText("Embed")).toBeInTheDocument();+ });++ it("should copy the dashboard app link when clicking the 'Copy link' button", async () => {+ setupDashboardSharingMenu({+ isAdmin: true,+ isPublicSharingEnabled: true,+ });+ await openMenu();+ await userEvent.click(screen.getByText("Copy link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/dashboard/1-my-cool-dashboard",+ ),+ );+ });++ it("should include the selected tab in the copied app link for multi-tab dashboards", async () => {+ setupDashboardSharingMenu({+ isAdmin: true,+ dashboard: {+ tabs: [+ createMockDashboardTab({ id: 1, name: "First Tab" }),+ createMockDashboardTab({ id: 2, name: "Second Tab" }),+ ],+ },+ dashboardState: { selectedTabId: 2 },+ });+ await openMenu();+ await userEvent.click(screen.getByText("Copy link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/dashboard/1-my-cool-dashboard?tab=2",+ ),+ );+ });++ it("should close the menu when opening the embed flow", async () => {+ setupDashboardSharingMenu({+ isAdmin: true,+ isEmbeddingEnabled: true,+ });+ await openMenu();+ await userEvent.click(screen.getByText("Embed"));+ await waitFor(() =>+ expect(screen.queryByTestId("sharing-menu")).not.toBeInTheDocument(),+ );});// note: if public sharing is disabled, the dashboard object provided by the backend should not have a UUID});describe("non-admins", () => {- it('should show a "Public link" menu item if public sharing is enabled and a public link exists already', async () => {+ it("should show both copy options when a public link exists", async () => {setupDashboardSharingMenu({isAdmin: false,isPublicSharingEnabled: true,hasPublicLink: true,});await openMenu();- expect(screen.getByText("Public link")).toBeInTheDocument();+ expect(screen.getByText("Copy link")).toBeInTheDocument();+ expect(screen.getByText("Copy public link")).toBeInTheDocument();+ expect(screen.getByText("Export as PDF")).toBeInTheDocument();+ expect(screen.queryByText("Public link")).not.toBeInTheDocument();expect(screen.queryByText("Create a public link"),).not.toBeInTheDocument();+ expect(+ screen.queryByText("Ask your admin to create a public link"),+ ).not.toBeInTheDocument();});- it("should not show a 'ask your admin to create a public link' menu item if public sharing is disabled", async () => {+ it("should copy the app link when clicking 'Copy link'", async () => {setupDashboardSharingMenu({isAdmin: false,- isPublicSharingEnabled: false,+ isPublicSharingEnabled: true,hasPublicLink: true,});await openMenu();+ await userEvent.click(screen.getByText("Copy link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/dashboard/1-my-cool-dashboard",+ ),+ );expect(- screen.getByText("Ask your admin to create a public link"),+ await screen.findByText("Link copied to clipboard"),).toBeInTheDocument();});- it("should show a 'ask your admin to create a public link' menu item if public sharing is enabled, but there is no existing public link", async () => {+ it("should copy the public link when clicking 'Copy public link'", async () => {setupDashboardSharingMenu({isAdmin: false,isPublicSharingEnabled: true,- hasPublicLink: false,+ hasPublicLink: true,});await openMenu();+ await userEvent.click(screen.getByText("Copy public link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/public/dashboard/1337bad801",+ ),+ );expect(- screen.getByText("Ask your admin to create a public link"),+ await screen.findByText("Public link copied to clipboard"),).toBeInTheDocument();});++ it("should hide 'Copy public link' when public sharing is disabled", async () => {+ setupDashboardSharingMenu({+ isAdmin: false,+ isPublicSharingEnabled: false,+ hasPublicLink: true,+ });+ await openMenu();+ expect(screen.getByText("Copy link")).toBeInTheDocument();+ expect(screen.getByText("Export as PDF")).toBeInTheDocument();+ expect(screen.queryByText("Copy public link")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Ask your admin to create a public link"),+ ).not.toBeInTheDocument();+ });++ it("should hide 'Copy public link' when there is no public link", async () => {+ setupDashboardSharingMenu({+ isAdmin: false,+ isPublicSharingEnabled: true,+ hasPublicLink: false,+ });+ await openMenu();+ expect(screen.getByText("Copy link")).toBeInTheDocument();+ expect(screen.getByText("Export as PDF")).toBeInTheDocument();+ expect(screen.queryByText("Copy public link")).not.toBeInTheDocument();+ });});});diff --git a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.module.css b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.module.cssdeleted file mode 100644index 7dd7ae89968..00000000000--- a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.module.css+++ /dev/null@@ -1,13 +0,0 @@-.copyButton {- position: relative;- top: 2px;- cursor: pointer;-- &:hover {- color: var(--mb-color-core-brand);- }-}--.removeLink {- white-space: nowrap;-}diff --git a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.tsx b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.tsxindex 27a2ebdd8bb..01f36eea2b5 100644--- a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.tsx+++ b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkCopyPanel.tsx@@ -1,19 +1,9 @@import type { MouseEventHandler } from "react";import { t } from "ttag";-import { CopyButton } from "metabase/common/components/CopyButton";+import { CopyTextInput } from "metabase/common/components/CopyTextInput";import type { ExportFormat } from "metabase/common/types/export";-import {- Anchor,- Box,- Group,- Stack,- Text,- TextInput,- Tooltip,-} from "metabase/ui";--import S from "./PublicLinkCopyPanel.module.css";+import { Anchor, Box, Group, Stack, Text, Tooltip } from "metabase/ui";export const PublicLinkCopyPanel = ({loading = false,@@ -37,74 +27,58 @@ export const PublicLinkCopyPanel = ({onCopy?: () => void;}) => (<Stack gap={0}>- <TextInput- readOnly+ <CopyTextInputdata-testid="public-link-input"placeholder={loading ? t`Loading…` : undefined}value={url ?? ""}- inputWrapperOrder={["label", "input", "error", "description"]}- rightSection={- url && (- <CopyButton className={S.copyButton} value={url} onCopy={onCopy} />- )- }+ onCopied={onCopy}/>- <Box pos="relative">- <Group- mt="sm"- pos="absolute"- w="100%"- justify="space-between"- align="center"- >- <Box>- {onRemoveLink && (- // The container is needed to center the tooltip on the anchor- <Tooltip- label={- <Text fw={700} c="inherit">- {removeTooltipLabel}- </Text>+ <Group mt="sm" justify="space-between" align="center">+ <Group gap="sm">+ {extensions &&+ extensions.length > 0 &&+ extensions.map((extension) => (+ <Anchor+ data-testid="extension-option"+ key={extension}+ tt="uppercase"+ c={+ extension === selectedExtension ? "core-brand" : "text-tertiary"+ }+ fw={700}+ onClick={() =>+ onChangeExtension?.(+ extension === selectedExtension ? null : extension,+ )}>- <Anchor- component="button"- className={S.removeLink}- fz="sm"- c="error"- fw={700}- onClick={onRemoveLink}- >- {removeButtonLabel}- </Anchor>- </Tooltip>- )}- </Box>- <Group gap="sm" justify="flex-end">- {extensions &&- extensions.length > 0 &&- extensions.map((extension) => (- <Anchor- data-testid="extension-option"- key={extension}- tt="uppercase"- c={- extension === selectedExtension- ? "core-brand"- : "text-tertiary"- }- fw={700}- onClick={() =>- onChangeExtension?.(- extension === selectedExtension ? null : extension,- )- }- >- {extension}- </Anchor>- ))}- </Group>+ {extension}+ </Anchor>+ ))}</Group>- </Box>+ <Box>+ {onRemoveLink && (+ // The container is needed to center the tooltip on the anchor+ <Tooltip+ label={+ <Text fw={700} c="inherit">+ {removeTooltipLabel}+ </Text>+ }+ >+ <Anchor+ component="button"+ style={{ whiteSpace: "nowrap" }}+ fz="sm"+ c="error"+ fw={700}+ onClick={onRemoveLink}+ >+ {removeButtonLabel}+ </Anchor>+ </Tooltip>+ )}+ </Box>+ </Group></Stack>);diff --git a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.tsx b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.tsxindex a1f89ed6a80..78517f1623d 100644--- a/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.tsx+++ b/frontend/src/metabase/embedding/components/PublicLinkPopover/PublicLinkPopover.tsx@@ -47,14 +47,6 @@ export const PublicLinkPopover = ({deletePublicLink();};- const getMinDropdownHeight = () => {- if (isAdmin || extensions.length > 0) {- return "10rem";- }-- return "auto";- };-return (<Popoveropened={isOpen}@@ -65,17 +57,18 @@ export const PublicLinkPopover = ({<Box onClick={isOpen ? onClose : undefined}>{target}</Box></Popover.Target><Popover.Dropdown>- <Box- p="lg"- w="28rem"- data-testid="public-link-popover-content"- mih={getMinDropdownHeight()}- >- <Title c="text-secondary" order={4}>{t`Public link`}</Title>+ <Box p="lg" w="28rem" data-testid="public-link-popover-content">+ <Title+ order={4}+ c="text-primary"+ fz="md"+ fw={700}+ lh="1.5rem"+ >{t`Public link`}</Title><Textcolor="text-secondary"size="sm"- mb="xs"+ mb="sm">{t`Anyone can view this if you give them the link.`}</Text><PublicLinkCopyPanelloading={loading}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/LinkCopiedTooltipLabel.tsx b/frontend/src/metabase/embedding/components/SharingMenu/LinkCopiedTooltipLabel.tsxnew file mode 100644index 00000000000..98e2b1b4e19--- /dev/null+++ b/frontend/src/metabase/embedding/components/SharingMenu/LinkCopiedTooltipLabel.tsx@@ -0,0 +1,14 @@+import { t } from "ttag";++import { Flex, Icon, Text } from "metabase/ui";++export function LinkCopiedTooltipLabel({ message }: { message?: string }) {+ return (+ <Flex gap="sm" align="center">+ <Icon name="verified_round" size={16} />+ <Text fz="md" lh="sm" c="inherit">+ {message ?? t`Link copied to clipboard`}+ </Text>+ </Flex>+ );+}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem.tsx b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem.tsxnew file mode 100644index 00000000000..45af1252f47--- /dev/null+++ b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem.tsx@@ -0,0 +1,74 @@+import { t } from "ttag";++import { CopyButton, Icon, Menu, Tooltip } from "metabase/ui";+import type { IconName } from "metabase-types/api";++import { LinkCopiedTooltipLabel } from "../LinkCopiedTooltipLabel";++// how long the copied-confirmation feedback stays visible+export const COPY_TIMEOUT_MS = 2000;++function CopyMenuItem({+ url,+ icon,+ label,+ copiedMessage,+ onCopied,+}: {+ url: string;+ icon: IconName;+ label: string;+ copiedMessage: string;+ onCopied?: () => void;+}) {+ return (+ <CopyButton value={url} timeout={COPY_TIMEOUT_MS}>+ {({ copied, copy }) => (+ <Tooltip+ label={<LinkCopiedTooltipLabel message={copiedMessage} />}+ opened={copied}+ >+ <Menu.Item+ leftSection={<Icon name={icon} aria-hidden />}+ closeMenuOnClick={false}+ onClick={() => {+ copy();+ onCopied?.();+ }}+ >+ {label}+ </Menu.Item>+ </Tooltip>+ )}+ </CopyButton>+ );+}++export function CopyLinkMenuItem({ url }: { url: string }) {+ return (+ <CopyMenuItem+ url={url}+ icon="link"+ label={t`Copy link`}+ copiedMessage={t`Link copied to clipboard`}+ />+ );+}++export function CopyPublicLinkMenuItem({+ url,+ onCopied,+}: {+ url: string;+ onCopied?: () => void;+}) {+ return (+ <CopyMenuItem+ url={url}+ icon="globe"+ label={t`Copy public link`}+ copiedMessage={t`Public link copied to clipboard`}+ onCopied={onCopied}+ />+ );+}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem.tsx b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem.tsxindex 94508a4e353..ad8bc0a6b2f 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem.tsx@@ -1,16 +1,8 @@import { t } from "ttag";-import { useSelector } from "metabase/redux";-import { getUserIsAdmin } from "metabase/selectors/user";import { Icon, Menu } from "metabase/ui";export function EmbedMenuItem({ onClick }: { onClick: () => void }) {- const isAdmin = useSelector(getUserIsAdmin);-- if (!isAdmin) {- return null;- }-return (<Menu.Itemdata-testid="embed-menu-embed-modal-item"diff --git a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem.tsx b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem.tsxindex f9934b8f2d0..691c471b5a3 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem.tsx@@ -1,11 +1,6 @@import { t } from "ttag";-import { Link } from "metabase/common/components/Link";-import { useSetting } from "metabase/common/hooks";-import CS from "metabase/css/core/index.css";-import { useSelector } from "metabase/redux";-import { getUserIsAdmin } from "metabase/selectors/user";-import { Button, Icon, Menu } from "metabase/ui";+import { Icon, Menu } from "metabase/ui";export function PublicLinkMenuItem({hasPublicLink,@@ -14,60 +9,12 @@ export function PublicLinkMenuItem({hasPublicLink: boolean;onClick: () => void;}) {- const isPublicSharingEnabled = useSetting("enable-public-sharing");- const isAdmin = useSelector(getUserIsAdmin);-- if (isAdmin) {- return (- <Menu.Item- data-testid="embed-menu-public-link-item"- leftSection={<Icon name="link" aria-hidden />}- onClick={onClick}- {...(!isPublicSharingEnabled && {- onClick: undefined,- component: "div",- disabled: true,- })}- >- {isPublicSharingEnabled ? (- hasPublicLink ? (- t`Public link`- ) : (- t`Create a public link`- )- ) : (- <>- {t`Public link`}- <Button- component={Link}- to="/admin/settings/public-sharing"- target="_blank"- variant="subtle"- h="auto"- lh="inherit"- ml="sm"- p={0}- bd={0}- className={CS.floatRight}- >- {t`Enable`}- </Button>- </>- )}- </Menu.Item>- );- }-return (<Menu.Item- data-testid="embed-menu-public-link-item"- leftSection={<Icon name="link" aria-hidden />}+ leftSection={<Icon name="globe" aria-hidden />}onClick={onClick}- disabled={!hasPublicLink}>- {hasPublicLink- ? t`Public link`- : t`Ask your admin to create a public link`}+ {hasPublicLink ? t`Public link` : t`Create a public link`}</Menu.Item>);}diff --git a/frontend/src/metabase/embedding/components/SharingMenu/SharingMenu.tsx b/frontend/src/metabase/embedding/components/SharingMenu/SharingMenu.tsxindex ef22bbb1392..0bcc2a9d72b 100644--- a/frontend/src/metabase/embedding/components/SharingMenu/SharingMenu.tsx+++ b/frontend/src/metabase/embedding/components/SharingMenu/SharingMenu.tsx@@ -1,16 +1,10 @@-import React, { type Ref, forwardRef } from "react";+import React from "react";import { t } from "ttag";import { ToolbarButton } from "metabase/common/components/ToolbarButton";import { Menu } from "metabase/ui";-export function SharingMenu({- children,- tooltip,-}: {- children: React.ReactNode;- tooltip?: string;-}) {+export function SharingMenu({ children }: { children: React.ReactNode }) {const hasNoChildren = !children || !React.Children.count(children);return (@@ -19,8 +13,8 @@ export function SharingMenu({<ToolbarButtonicon="share"data-testid="sharing-menu-button"- tooltipLabel={tooltip ?? t`Sharing`}- aria-label={tooltip ?? t`Sharing`}+ tooltipLabel={t`Share`}+ aria-label={t`Share`}disabled={hasNoChildren}/></Menu.Target>@@ -29,27 +23,26 @@ export function SharingMenu({);}-export const SharingButton = forwardRef(function _SharingButton(- {- tooltip,- onClick,- disabled,- }: {- tooltip?: string;- onClick?: () => void;- disabled?: boolean;- },- ref: Ref<HTMLButtonElement>,-) {+export function SharingButton({+ tooltip,+ "aria-label": ariaLabel,+ onClick,+}: {+ tooltip?: React.ReactNode;+ "aria-label"?: string;+ onClick?: () => void;+}) {return (<ToolbarButton- ref={ref}icon="share"data-testid="sharing-menu-button"- tooltipLabel={tooltip ?? t`Sharing`}- aria-label={tooltip ?? t`Sharing`}+ tooltipLabel={tooltip ?? t`Share`}+ // aria-label must be a string; keep the accessible name stable when the+ // tooltip is a non-string node (e.g. the copied-confirmation flash)+ aria-label={+ ariaLabel ?? (typeof tooltip === "string" ? tooltip : t`Share`)+ }onClick={onClick}- disabled={disabled}/>);-});+}diff --git a/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx b/frontend/src/metabase/home/components/Onboarding/Onboarding.tsxindex 52d0089fcdb..5a2d10b001b 100644--- a/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx+++ b/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx@@ -536,7 +536,7 @@ export const Onboarding = () => {className={S.inlineIcon}/>)} ${(- <b key="sharing">{t`Sharing`}</b>+ <b key="sharing">{t`Share`}</b>)} icon on the top bar, then click on ${(<Iconkey="subscription-icon"diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsxindex 820022b168b..441178234d7 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.enterprise.unit.spec.tsx@@ -3,78 +3,88 @@ import userEvent from "@testing-library/user-event";import { screen, waitFor } from "__support__/ui";import { createMockCollection } from "metabase-types/api/mocks";-import { setupQuestionSharingMenu } from "./tests/setup";+import { openMenu, setupQuestionSharingMenu } from "./tests/setup";describe("QuestionSharingMenu > Enterprise", () => {- describe("non-admins", () => {- describe("alerts permission disabled", () => {- it('should show a "Public link" button item if public sharing is enabled and the user lacks alerts permissions', async () => {- setupQuestionSharingMenu({- canManageSubscriptions: false,- isPublicSharingEnabled: true,- hasPublicLink: true,- isEnterprise: true,- });- const sharingButton = screen.getByTestId("sharing-menu-button");+ beforeEach(() => {+ jest.mocked(navigator.clipboard.writeText).mockClear();+ });- expect(sharingButton).toBeEnabled();- expect(sharingButton).toHaveAttribute("aria-label", "Public link");+ describe("non-admins", () => {+ it("shows a sharing menu with both copy options when a public link exists", async () => {+ setupQuestionSharingMenu({+ canManageSubscriptions: false,+ isPublicSharingEnabled: true,+ hasPublicLink: true,+ isEnterprise: true,});+ expect(screen.getByTestId("sharing-menu-button")).toHaveAttribute(+ "aria-label",+ "Share",+ );+ await openMenu();+ expect(screen.getByText("Copy link")).toBeInTheDocument();+ expect(screen.getByText("Copy public link")).toBeInTheDocument();+ });- it("clicking the sharing button should open the public link popover", async () => {- setupQuestionSharingMenu({- canManageSubscriptions: false,- isPublicSharingEnabled: true,- hasPublicLink: true,- isEnterprise: true,- });+ it("copies the public link from the menu instead of opening a popover", async () => {+ setupQuestionSharingMenu({+ canManageSubscriptions: false,+ isPublicSharingEnabled: true,+ hasPublicLink: true,+ isEnterprise: true,+ });- await userEvent.click(screen.getByTestId("sharing-menu-button"));+ await openMenu();+ await userEvent.click(screen.getByText("Copy public link"));- // popover content mounts asynchronously after the click- expect(- await screen.findByTestId("public-link-popover-content"),- ).toBeInTheDocument();- const input = screen.getByTestId("public-link-input");- expect(input).toHaveDisplayValue(+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith("http://localhost:3000/public/question/1337bad801",- );+ ),+ );+ expect(+ screen.queryByTestId("public-link-popover-content"),+ ).not.toBeInTheDocument();+ });- // the input drops its loading placeholder once the link-loading- // effect resolves- await waitFor(() => expect(input).not.toHaveAttribute("placeholder"));+ it("copies the app link directly without an admin prompt when public sharing is disabled", async () => {+ setupQuestionSharingMenu({+ isPublicSharingEnabled: false,+ hasPublicLink: true,+ canManageSubscriptions: false,+ isEnterprise: true,});+ const sharingButton = screen.getByTestId("sharing-menu-button");- it("should show a 'ask your admin to create a public link' tooltip if public sharing is disabled", async () => {- setupQuestionSharingMenu({- isPublicSharingEnabled: false,- hasPublicLink: true,- canManageSubscriptions: false,- isEnterprise: true,- });- const sharingButton = screen.getByTestId("sharing-menu-button");+ expect(sharingButton).toHaveAttribute("aria-label", "Copy link");+ await userEvent.click(sharingButton);++ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/question/1-my-cool-question",+ );+ expect(+ screen.queryByText("Ask your admin to create a public link"),+ ).not.toBeInTheDocument();+ });- expect(sharingButton).toBeDisabled();- expect(sharingButton).toHaveAttribute(- "aria-label",- "Ask your admin to create a public link",- );+ it("copies the app link directly without an admin prompt when there is no public link", async () => {+ setupQuestionSharingMenu({+ isPublicSharingEnabled: true,+ canManageSubscriptions: false,+ hasPublicLink: false,});+ const sharingButton = screen.getByTestId("sharing-menu-button");- it("should show a 'ask your admin to create a public link' menu item if public sharing is enabled, but there is no existing public link", async () => {- setupQuestionSharingMenu({- isPublicSharingEnabled: true,- canManageSubscriptions: false,- hasPublicLink: false,- });- const sharingButton = screen.getByTestId("sharing-menu-button");+ expect(sharingButton).toHaveAttribute("aria-label", "Copy link");+ await userEvent.click(sharingButton);- expect(sharingButton).toBeDisabled();- expect(sharingButton).toHaveAttribute(- "aria-label",- "Ask your admin to create a public link",- );- });+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/question/1-my-cool-question",+ );+ expect(+ screen.queryByText("Ask your admin to create a public link"),+ ).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsxindex c6e50d34521..98e27721113 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx@@ -1,7 +1,14 @@+import { useMemo } from "react";import { t } from "ttag";import { isInstanceAnalyticsCollection } from "metabase/collections/utils";import { useSetting } from "metabase/common/hooks";+import { LinkCopiedTooltipLabel } from "metabase/embedding/components/SharingMenu/LinkCopiedTooltipLabel";+import {+ COPY_TIMEOUT_MS,+ CopyLinkMenuItem,+ CopyPublicLinkMenuItem,+} from "metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem";import { EmbedMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem";import { PublicLinkMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem";import {@@ -11,34 +18,27 @@ import {import type { QuestionSharingModalType } from "metabase/embedding/components/SharingMenu/types";import { GUEST_EMBED_EMBEDDING_TYPE } from "metabase/embedding/constants";import { useSharingModal } from "metabase/embedding/hooks/use-sharing-modal";+import { trackPublicLinkCopied } from "metabase/embedding/lib/analytics";import { MODAL_TYPES } from "metabase/querying/constants";import { useDispatch, useSelector } from "metabase/redux";import { setUIControls } from "metabase/redux/query-builder";+import { getUserIsAdmin } from "metabase/selectors/user";+import { Box, CopyButton, Flex } from "metabase/ui";import {- canManageSubscriptions as canManageSubscriptionsSelector,- getUserIsAdmin,-} from "metabase/selectors/user";-import { Box, Flex } from "metabase/ui";+ publicQuestion as getPublicQuestionUrl,+ question as getQuestionUrl,+} from "metabase/urls";import type Question from "metabase-lib/v1/Question";import { QuestionPublicLinkPopover } from "../../../../sidebars/QuestionInfoSidebar/QuestionPublicLinkPopover/QuestionPublicLinkPopover";export function QuestionSharingMenu({ question }: { question: Question }) {const dispatch = useDispatch();- const { modalType, setModalType } = useSharingModal<QuestionSharingModalType>(- {- resource: question.card(),- resourceType: "question",- },- );- const hasPublicLink = !!question?.publicUUID?.();+ const isAdmin = useSelector(getUserIsAdmin);const isModel = question.type() === "model";const isArchived = question.isArchived();- const isPublicSharingEnabled = useSetting("enable-public-sharing");- const isAdmin = useSelector(getUserIsAdmin);const collection = question.collection();const isAnalytics = collection && isInstanceAnalyticsCollection(collection);- const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);if (isModel || isArchived || isAnalytics) {return null;@@ -59,53 +59,96 @@ export function QuestionSharingMenu({ question }: { question: Question }) {);}- if (- !isAdmin &&- (!isPublicSharingEnabled || !hasPublicLink) &&- !canManageSubscriptions- ) {- return (- <SharingButton- tooltip={t`Ask your admin to create a public link`}- disabled- />- );- }+ return isAdmin ? (+ <AdminQuestionSharingMenu question={question} />+ ) : (+ <NonAdminQuestionSharingMenu question={question} />+ );+}- if (!isAdmin && hasPublicLink && !canManageSubscriptions) {- return (- <Flex>- <SharingButton- tooltip={t`Public link`}- onClick={() => setModalType("question-public-link")}+// Building the question URL converts the whole query, so don't redo it per render.+function useQuestionAppUrl(question: Question) {+ const siteUrl = useSetting("site-url");++ return useMemo(+ () => `${siteUrl}${getQuestionUrl(question)}`,+ [siteUrl, question],+ );+}++function CopyQuestionLinkMenuItem({ question }: { question: Question }) {+ return <CopyLinkMenuItem url={useQuestionAppUrl(question)} />;+}++function AdminQuestionSharingMenu({ question }: { question: Question }) {+ const { modalType, setModalType } = useSharingModal<QuestionSharingModalType>(+ {+ resource: question.card(),+ resourceType: "question",+ },+ );+ const isPublicSharingEnabled = useSetting("enable-public-sharing");++ return (+ <Flex>+ <SharingMenu>+ <CopyQuestionLinkMenuItem question={question} />+ {isPublicSharingEnabled && (+ <PublicLinkMenuItem+ hasPublicLink={Boolean(question.publicUUID?.())}+ onClick={() => setModalType("question-public-link")}+ />+ )}+ <EmbedMenuItem+ onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}/>+ </SharingMenu>+ {modalType === "question-public-link" && (<QuestionPublicLinkPopoverquestion={question}target={<Box h="2rem" />}- isOpen={modalType === "question-public-link"}+ isOpenonClose={() => setModalType(null)}/>- </Flex>- );+ )}+ </Flex>+ );+}++// Non-admins can't create public links. When one already exists they get a+// menu with both copy options; otherwise the button copies the app link directly.+function NonAdminQuestionSharingMenu({ question }: { question: Question }) {+ const publicUuid = question.publicUUID?.();++ if (!publicUuid) {+ return <CopyQuestionLinkButton question={question} />;}return (- <Flex>- <SharingMenu>- <PublicLinkMenuItem- hasPublicLink={hasPublicLink}- onClick={() => setModalType("question-public-link")}- />- <EmbedMenuItem- onClick={() => setModalType(GUEST_EMBED_EMBEDDING_TYPE)}- />- </SharingMenu>- <QuestionPublicLinkPopover- question={question}- target={<Box h="2rem" />}- isOpen={modalType === "question-public-link"}- onClose={() => setModalType(null)}+ <SharingMenu>+ <CopyQuestionLinkMenuItem question={question} />+ <CopyPublicLinkMenuItem+ url={getPublicQuestionUrl({ uuid: publicUuid })}+ onCopied={() =>+ trackPublicLinkCopied({ artifact: "question", format: "html" })+ }/>- </Flex>+ </SharingMenu>+ );+}++function CopyQuestionLinkButton({ question }: { question: Question }) {+ const url = useQuestionAppUrl(question);++ return (+ <CopyButton value={url} timeout={COPY_TIMEOUT_MS}>+ {({ copied, copy }) => (+ <SharingButton+ tooltip={copied ? <LinkCopiedTooltipLabel /> : t`Copy link`}+ aria-label={t`Copy link`}+ onClick={copy}+ />+ )}+ </CopyButton>);}diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsxindex 2b46fef044b..e831d940a6d 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx@@ -5,6 +5,10 @@ import { screen, waitFor } from "__support__/ui";import { openMenu, setupQuestionSharingMenu } from "./tests/setup";describe("QuestionSharingMenu", () => {+ beforeEach(() => {+ jest.mocked(navigator.clipboard.writeText).mockClear();+ });+it("should not render anything if the question is a model", async () => {await setupQuestionSharingMenu({question: { type: "model" },@@ -12,13 +16,13 @@ describe("QuestionSharingMenu", () => {expect(screen.queryByTestId("sharing-menu-button")).not.toBeInTheDocument();});- it("should have a 'sharing' tooltip by default", async () => {+ it("should have a 'share' tooltip by default", async () => {await setupQuestionSharingMenu({isAdmin: true,});expect(screen.getByTestId("sharing-menu-button")).toHaveAttribute("aria-label",- "Sharing",+ "Share",);});@@ -90,64 +94,120 @@ describe("QuestionSharingMenu", () => {).not.toBeInTheDocument();});- it('should show an "Enable" link if public sharing is disabled', async () => {+ it("should hide the public link option if public sharing is disabled", async () => {await setupQuestionSharingMenu({isAdmin: true,isPublicSharingEnabled: false,});await openMenu();- expect(screen.getByText("Public link")).toBeInTheDocument();- expect(screen.getByText("Enable")).toBeInTheDocument();+ expect(screen.queryByText("Public link")).not.toBeInTheDocument();+ expect(screen.queryByText("Enable")).not.toBeInTheDocument();expect(screen.queryByText("Create a public link"),).not.toBeInTheDocument();+ expect(screen.getByText("Embed")).toBeInTheDocument();});// note: if public sharing is disabled, the dashboard object provided by the backend should not have a UUID});describe("non-admins", () => {- it('should show a "Public link" menu item if there is a public link for the question', async () => {+ it("should show a sharing menu with both copy options when a public link exists", async () => {await setupQuestionSharingMenu({isAdmin: false,isPublicSharingEnabled: true,hasPublicLink: true,});+ expect(screen.getByTestId("sharing-menu-button")).toHaveAttribute(+ "aria-label",+ "Share",+ );await openMenu();- expect(screen.getByText("Public link")).toBeInTheDocument();+ expect(screen.getByText("Copy link")).toBeInTheDocument();+ expect(screen.getByText("Copy public link")).toBeInTheDocument();+ expect(screen.queryByText("Embed")).not.toBeInTheDocument();});- it('should show an "Ask your admin to create a public link" menu item if there is no public link for the question', async () => {+ it("should copy the app link from the menu", async () => {await setupQuestionSharingMenu({isAdmin: false,isPublicSharingEnabled: true,- hasPublicLink: false,+ hasPublicLink: true,});await openMenu();+ await userEvent.click(screen.getByText("Copy link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/question/1-my-cool-question",+ ),+ );expect(- screen.getByText("Ask your admin to create a public link"),+ await screen.findByText("Link copied to clipboard"),).toBeInTheDocument();});++ it("should copy the public link from the menu", async () => {+ await setupQuestionSharingMenu({+ isAdmin: false,+ isPublicSharingEnabled: true,+ hasPublicLink: true,+ });+ await openMenu();+ await userEvent.click(screen.getByText("Copy public link"));+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/public/question/1337bad801",+ ),+ );+ expect(+ await screen.findByText("Public link copied to clipboard"),+ ).toBeInTheDocument();+ });++ it("should copy the app link directly when there is no public link", async () => {+ await setupQuestionSharingMenu({+ isAdmin: false,+ isPublicSharingEnabled: true,+ hasPublicLink: false,+ });+ const button = screen.getByTestId("sharing-menu-button");+ expect(button).toHaveAttribute("aria-label", "Copy link");++ await userEvent.click(button);+ await userEvent.hover(button);++ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ "http://localhost:3000/question/1-my-cool-question",+ );+ expect(+ await screen.findByText("Link copied to clipboard"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Ask your admin to create a public link"),+ ).not.toBeInTheDocument();+ });});});describe("embedding", () => {describe("non-admins", () => {- it("should not show the 'Embed' menu item if embedding is enabled", async () => {+ it("should never expose the 'Embed' option if embedding is enabled", async () => {await setupQuestionSharingMenu({isAdmin: false,isEmbeddingEnabled: true,+ hasPublicLink: true,+ isPublicSharingEnabled: true,});- await openMenu();expect(screen.queryByText("Embed")).not.toBeInTheDocument();});- it("should not show the 'Embed' menu item if embedding is disabled", async () => {+ it("should never expose the 'Embed' option if embedding is disabled", async () => {await setupQuestionSharingMenu({isAdmin: false,isEmbeddingEnabled: false,+ hasPublicLink: true,+ isPublicSharingEnabled: true,});- await openMenu();expect(screen.queryByText("Embed")).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsxindex 116a83446d9..deb863b78fe 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/tests/setup.tsx@@ -148,14 +148,12 @@ export async function setupQuestionSharingMenu({{ storeInitialState: state },);- // QuestionSharingMenu eagerly mounts QuestionPublicLinkPopover, whose- // useAsync hook flips its loading state shortly after mount. Wait for the- // sharing menu button to settle so that async update stays wrapped in act.- // Some scenarios (models, archived questions) render nothing at all, so we- // only wait when the button is expected to appear.+ // Wait for the admin menu button to settle so async endpoint mocks resolve+ // inside act. Non-admin menus render synchronously, and model/archived+ // questions render nothing at all.const isModel = questionOverrides.type === "model";const isArchived = questionOverrides.archived === true;- if (!isModel && !isArchived) {+ if (isAdmin && !isModel && !isArchived) {await screen.findByTestId("sharing-menu-button");}}diff --git a/frontend/src/metabase/query_builder/reducers.ts b/frontend/src/metabase/query_builder/reducers.tsindex 256244d5546..1b886b42fb7 100644--- a/frontend/src/metabase/query_builder/reducers.ts+++ b/frontend/src/metabase/query_builder/reducers.ts@@ -621,96 +621,68 @@ export const selectedTimelineEventIds = createReducer<number[]>(},);+type CardPayloadAction = {+ type: string;+ payload: Card;+};++type NestedCardPayloadAction = {+ type: string;+ payload: {+ card: Card;+ };+};+// the card that is actively being worked onexport const card = createReducer<Card | null>(null, (builder) => {builder.addCase(RESET_QB, () => null).addCase(CLOSE_QB, () => null)- .addCase<- string,- {- type: string;- payload: {- card: Card;- };- }- >(INITIALIZE_QB, (state, action) =>+ .addCase<string, NestedCardPayloadAction>(INITIALIZE_QB, (state, action) =>action.payload ? action.payload.card : null,)- .addCase<- string,- {- type: string;- payload: Card;- }- >(SOFT_RELOAD_CARD, (state, action) => action.payload)- .addCase<- string,- {- type: string;- payload: Card;- }- >(RELOAD_CARD, (state, action) => action.payload)- .addCase<- string,- {- type: string;- payload: {- card: Card;- };- }- >(SET_CARD_AND_RUN, (state, action) => action.payload.card)- .addCase<- string,- {- type: string;- payload: Card;- }- >(API_CREATE_QUESTION, (state, action) => action.payload)- .addCase<- string,- {- type: string;- payload: Card;- }- >(API_UPDATE_QUESTION, (state, action) => action.payload)- .addCase<- string,- {- type: string;- payload: {- card: Card;- };- }- >(CANCEL_QUESTION_CHANGES, (state, action) => action.payload.card)- .addCase<- string,- {- type: string;- payload: {- card: Card;- };- }- >(UPDATE_QUESTION, (state, action) => action.payload.card)- .addCase<- string,- {- type: string;- payload: {- card: Card;+ .addCase<string, CardPayloadAction>(+ SOFT_RELOAD_CARD,+ (state, action) => action.payload,+ )+ .addCase<string, CardPayloadAction>(+ RELOAD_CARD,+ (state, action) => action.payload,+ )+ .addCase<string, NestedCardPayloadAction>(+ SET_CARD_AND_RUN,+ (state, action) => action.payload.card,+ )+ .addCase<string, CardPayloadAction>(+ API_CREATE_QUESTION,+ (state, action) => action.payload,+ )+ .addCase<string, CardPayloadAction>(+ API_UPDATE_QUESTION,+ (state, action) => action.payload,+ )+ .addCase<string, NestedCardPayloadAction>(+ CANCEL_QUESTION_CHANGES,+ (state, action) => action.payload.card,+ )+ .addCase<string, NestedCardPayloadAction>(+ UPDATE_QUESTION,+ (state, action) => action.payload.card,+ )+ .addCase<string, NestedCardPayloadAction>(+ QUERY_COMPLETED,+ (state, action) => {+ if (!state) {+ return state;+ }+ return {+ ...state,+ display: action.payload.card.display,+ result_metadata: action.payload.card.result_metadata,+ visualization_settings: action.payload.card.visualization_settings,};- }- >(QUERY_COMPLETED, (state, action) => {- if (!state) {- return state;- }- return {- ...state,- display: action.payload.card.display,- result_metadata: action.payload.card.result_metadata,- visualization_settings: action.payload.card.visualization_settings,- };- })+ },+ ).addMatcher(createCardPublicLink.matchFulfilled, (state, action) => {if (!state) {return state;