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
add support for entity id on #scrollTo (#84851)
Nicolò Pretto17c25d1c2299
diff --git a/frontend/src/metabase/routes-stable-id-aware.tsx b/frontend/src/metabase/routes-stable-id-aware.tsxindex 99fd0b81c62..40b65ec6dd2 100644--- a/frontend/src/metabase/routes-stable-id-aware.tsx+++ b/frontend/src/metabase/routes-stable-id-aware.tsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useState } from "react";import { match } from "ts-pattern";+import _ from "underscore";import { NotFound } from "metabase/common/components/ErrorPages";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";@@ -9,14 +10,20 @@ import {useParams,useSearchParams,} from "metabase/router";+import { parseHashOptions, stringifyHashOptions } from "metabase/utils/browser";import { isBaseEntityID } from "metabase-types/api/entity-id";import {type TranslateEntityIdResponse,useTranslateEntityIdQuery,} from "./api/entity-id";-type ResourceType = "dashboard" | "collection" | "card" | "dashboard-tab";-type ParamType = "param" | "search";+type ResourceType =+ | "dashboard"+ | "collection"+ | "card"+ | "dashboard-tab"+ | "dashboard-card";+type ParamType = "param" | "search" | "hash";type ParamConfig = {name: string;@@ -40,23 +47,26 @@ export const EntityIdRedirect = ({}: EntityIdRedirectProps) => {const navigate = useNavigate();const params = useParams();- const location = useLocation();+ const { pathname, search, hash } = useLocation();const [searchParams] = useSearchParams();- const currentUrl = location.pathname + location.search;const paramsWithValues: ParamWithValue[] = useMemo(() => {- // add the value from the params or the query+ // add the value from the params, the query or the hashreturn parametersToTranslate.map((config) => {const value = match(config.type).with("param", () => params[config.name]).with("search", () => searchParams.get(config.name) ?? undefined)+ .with("hash", () => {+ const hashValue = parseHashOptions(hash)[config.name];+ return typeof hashValue === "string" ? hashValue : undefined;+ }).exhaustive();return {...config,value,};});- }, [parametersToTranslate, params, searchParams]);+ }, [parametersToTranslate, params, searchParams, hash]);const entityIdsToTranslate = useMemo(() => {// formats the entity ids in the format {resourceType: [entityId1, entityId2]}@@ -83,7 +93,9 @@ export const EntityIdRedirect = ({useEffect(() => {if (!isLoading) {const { shouldRedirect, url, notFound } = handleResults({- currentUrl,+ pathname,+ search,+ hash,paramsWithValues,entity_ids,});@@ -97,7 +109,16 @@ export const EntityIdRedirect = ({navigate(url.replace("/entity/", "/"));}}- }, [currentUrl, entity_ids, isError, isLoading, paramsWithValues, navigate]);+ }, [+ pathname,+ search,+ hash,+ entity_ids,+ isError,+ isLoading,+ paramsWithValues,+ navigate,+ ]);if (isError) {throw error;@@ -113,31 +134,55 @@ export const EntityIdRedirect = ({};function handleResults({- currentUrl,+ pathname,+ search,+ hash,paramsWithValues,entity_ids,}: {- currentUrl: string;+ pathname: string;+ search: string;+ hash: string;paramsWithValues: ParamWithValue[];entity_ids: TranslateEntityIdResponse | undefined;}) {let shouldRedirect = false;- let url = currentUrl;let notFound = false;- for (const { value } of paramsWithValues) {- if (isBaseEntityID(value)) {- const mappedEntityId = entity_ids?.[value];- // if the entity id is found, we replace it with the numeric id- if (mappedEntityId?.id) {- shouldRedirect = true;- url = url.replace(value, String(mappedEntityId.id));- } else {- // if it's not found we show a 404- notFound = true;- }+ let nextPathname = pathname;+ let nextSearch = search;+ let nextHash = hash;++ for (const { name, type, value } of paramsWithValues) {+ if (!isBaseEntityID(value)) {+ continue;+ }+ const id = entity_ids?.[value]?.id;++ if (type === "hash") {+ // we don't show a 404 for missing hash params: the only one we have today+ // is #scrollTo, the id of the dashcard to scroll to, and if it's missing we+ // don't want to show an error but just drop it+ const hashOptions = parseHashOptions(nextHash);+ const hashString = stringifyHashOptions(+ id ? { ...hashOptions, [name]: String(id) } : _.omit(hashOptions, name),+ );+ nextHash = hashString ? `#${hashString}` : "";+ } else if (!id) {+ notFound = true;+ } else if (type === "param") {+ shouldRedirect = true;+ nextPathname = nextPathname.replace(value, String(id));+ } else {+ shouldRedirect = true;+ nextSearch = nextSearch.replace(value, String(id));}}- return { shouldRedirect, url, notFound };++ return {+ shouldRedirect,+ url: nextPathname + nextSearch + nextHash,+ notFound,+ };}export function createEntityIdRedirect(config: {diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsxindex f3be4bcd689..8cdee9f8363 100644--- a/frontend/src/metabase/routes.tsx+++ b/frontend/src/metabase/routes.tsx@@ -414,6 +414,11 @@ export const getRoutes = (store: AppStore): RouteObject[] => [resourceType: "dashboard-tab",type: "search",},+ {+ name: "scrollTo",+ resourceType: "dashboard-card",+ type: "hash",+ },],}),},diff --git a/frontend/src/metabase/routes.unit.spec.tsx b/frontend/src/metabase/routes.unit.spec.tsxindex 4740da84631..78d505ce112 100644--- a/frontend/src/metabase/routes.unit.spec.tsx+++ b/frontend/src/metabase/routes.unit.spec.tsx@@ -7,6 +7,7 @@ import {setupDashboardQuestionCandidatesEndpoint,setupUserKeyValueEndpoints,} from "__support__/server-mocks";+import { setupEntityIdEndpoint } from "__support__/server-mocks/entity-id";import { renderRoutes, renderWithProviders, screen } from "__support__/ui";import { setup as setupAccountPassword } from "metabase/account/password/containers/UserPasswordApp/tests/setup";import { getUser } from "metabase/current-user";@@ -15,6 +16,7 @@ import { Route } from "metabase/router";import { defer } from "metabase/utils/promise";import type { User } from "metabase-types/api";import { createMockUser } from "metabase-types/api/mocks";+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";import { LegacyBrowseRedirect, getRoutes } from "./routes";@@ -75,6 +77,10 @@ jest.mock("metabase/collections/components/CollectionLanding", () => {return { __esModule: true, default: () => <Outlet /> };});+jest.mock("metabase/dashboard/containers/DashboardApp/DashboardApp", () => ({+ DashboardApp: () => <div>dashboard app</div>,+}));+function setupAppRoutes({initialRoute,user = createMockUser({ is_superuser: true }),@@ -316,3 +322,82 @@ describe("collection modal routes", () => {expect(screen.getAllByRole("dialog")).toHaveLength(1);});});++describe("dashboard entity-id deep links", () => {+ const DASHBOARD_EID = createMockEntityId("xBLdW9FsgRuB2HGhWiBa_");+ const TAB_EID = createMockEntityId("N-o1tJ9swdO4YJycqMA8P");+ const DASHCARD_EID = createMockEntityId("19JbScZRjz5mSQ7chtjuY");+ const UNKNOWN_DASHCARD_EID = "unknownDashcardEid___";+ const DASHBOARD_ID = 1;+ const TAB_ID = 2;+ const DASHCARD_ID = 25;++ type SetupOpts = {+ initialRoute: string;+ };++ function setup({ initialRoute }: SetupOpts) {+ setupEntityIdEndpoint({+ dashboard: { [DASHBOARD_EID]: DASHBOARD_ID },+ "dashboard-tab": { [TAB_EID]: TAB_ID },+ "dashboard-card": { [DASHCARD_EID]: DASHCARD_ID },+ });++ const { router } = setupAppRoutes({ initialRoute });+ return router;+ }++ it("resolves the dashboard entity_id in the path to its numeric id", async () => {+ const router = setup({+ initialRoute: `/dashboard/entity/${DASHBOARD_EID}`,+ });++ await waitFor(() =>+ expect(router?.location.pathname).toBe(`/dashboard/${DASHBOARD_ID}`),+ );+ expect(await screen.findByText("dashboard app")).toBeInTheDocument();+ });++ it("translates the tab and the scrollTo dashcard entity_ids", async () => {+ const router = setup({+ initialRoute: `/dashboard/entity/${DASHBOARD_EID}?tab=${TAB_EID}#scrollTo=${DASHCARD_EID}`,+ });++ await waitFor(() =>+ expect(router?.location.pathname).toBe(`/dashboard/${DASHBOARD_ID}`),+ );+ expect(router?.location.search).toBe(`?tab=${TAB_ID}`);+ expect(router?.location.hash).toBe(`#scrollTo=${DASHCARD_ID}`);+ });++ it("drops a scrollTo entity_id that doesn't exist and keeps the rest of the hash", async () => {+ const router = setup({+ initialRoute: `/dashboard/entity/${DASHBOARD_EID}#scrollTo=${UNKNOWN_DASHCARD_EID}&fullscreen`,+ });++ expect(await screen.findByText("dashboard app")).toBeInTheDocument();+ expect(router?.location.pathname).toBe(`/dashboard/${DASHBOARD_ID}`);+ expect(router?.location.hash).toBe("#fullscreen");+ });++ it("keeps a hash without entity_ids as it is", async () => {+ const router = setup({+ initialRoute: `/dashboard/entity/${DASHBOARD_EID}#scrollTo=${DASHCARD_ID}&refresh=60`,+ });++ await waitFor(() =>+ expect(router?.location.pathname).toBe(`/dashboard/${DASHBOARD_ID}`),+ );+ expect(router?.location.hash).toBe(`#scrollTo=${DASHCARD_ID}&refresh=60`);+ });++ it("shows a 404 for a tab entity_id that doesn't exist, even when it starts with a number", async () => {+ setup({+ initialRoute: `/dashboard/entity/${DASHBOARD_EID}?tab=${"12".padEnd(21, "x")}`,+ });++ expect(+ await screen.findByText("We're a little lost..."),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/test/__support__/server-mocks/entity-id.ts b/frontend/test/__support__/server-mocks/entity-id.tsindex b2d420387f5..34529f22bb9 100644--- a/frontend/test/__support__/server-mocks/entity-id.ts+++ b/frontend/test/__support__/server-mocks/entity-id.ts@@ -5,13 +5,17 @@ import type {BaseEntityId,CardId,CollectionId,+ DashCardId,DashboardId,+ DashboardTabId,} from "metabase-types/api";type SUPPORTED_ENTITIES = {dashboard: DashboardId;card: CardId;collection: CollectionId;+ "dashboard-tab": DashboardTabId;+ "dashboard-card": DashCardId;};type EntityIdMappingParameter = Partial<{@@ -24,47 +28,42 @@ type EntityIdMappingParameter = Partial<{export function setupEntityIdEndpoint(entityIdMappings: EntityIdMappingParameter,) {- fetchMock.post(- "path:/api/eid-translation/translate",- async (_url: string, options: RequestInit) => {- // Unjustified type cast. FIXME- const body = JSON.parse(options.body as string) as {- entity_ids: TranslateEntityIdRequest;- };- const requestedIdMap = body?.entity_ids ?? {};- const allRequestedPairs = Object.entries(requestedIdMap).flatMap(- ([typeString, idArray]) =>- (idArray ?? []).map((id) => ({- entityType: typeString,- entityId: id,- })),- );- const resultMapEntries = allRequestedPairs.map(- ({- entityType,- entityId,- }: {- entityType: string;- entityId: BaseEntityId;- }) => {- const mappedValue =- // Unjustified type cast. FIXME- entityIdMappings[entityType as keyof SUPPORTED_ENTITIES]?.[- entityId- ];- const responseItem =- mappedValue !== undefined- ? { status: "ok", id: mappedValue, type: entityType }- : { status: "not-found", id: null, type: entityType };- return [entityId, responseItem];- },- );+ fetchMock.post("path:/api/eid-translation/translate", async (call) => {+ // translateEntityId in metabase/api/entity-id.ts sends this body+ const body = (await call.request?.json()) as {+ entity_ids: TranslateEntityIdRequest;+ };+ const requestedIdMap = body?.entity_ids ?? {};+ const allRequestedPairs = Object.entries(requestedIdMap).flatMap(+ ([typeString, idArray]) =>+ (idArray ?? []).map((id) => ({+ entityType: typeString,+ entityId: id,+ })),+ );+ const resultMapEntries = allRequestedPairs.map(+ ({+ entityType,+ entityId,+ }: {+ entityType: string;+ entityId: BaseEntityId;+ }) => {+ const mappedValue =+ // Unjustified type cast. FIXME+ entityIdMappings[entityType as keyof SUPPORTED_ENTITIES]?.[entityId];+ const responseItem =+ mappedValue !== undefined+ ? { status: "ok", id: mappedValue, type: entityType }+ : { status: "not-found", id: null, type: entityType };+ return [entityId, responseItem];+ },+ );- const responseMap = Object.fromEntries(resultMapEntries);+ const responseMap = Object.fromEntries(resultMapEntries);- return {- entity_ids: responseMap,- };- },- );+ return {+ entity_ids: responseMap,+ };+ });}